import React, { Component } from "react";
import TabelContent from "../../../common/tabelContent";
import {
  Button,
  Modal,
  Tag,
  Form,
  DatePicker,
  Input,
  message,
  Upload,
  Icon,
  Radio,
  Popconfirm,
  Table,
} from "antd";
import ImgList from "../../../common/imgList";
import $ from "jquery/src/ajax";
import { splitUrl } from "../../../tools.js";
import download from "downloadjs";
import TablePopup from "./tablePopup";
import { element } from "prop-types";
const { TextArea } = Input;
const RadioGroup = Radio.Group;
class LegalRecd extends Component {
  constructor(props) {
    super(props);
    this.state = {
      columns: [
        {
          title: "序号",
          dataIndex: "key",
          key: "key",
          width: 45,
        },
        {
          title: "操作人名称",
          dataIndex: "adminName",
          key: "adminName",
          width: 80,
        },
        {
          title: "客户名称",
          dataIndex: "userName",
          key: "userName",
          width: 140,
        },
        {
          title: "法务时间",
          dataIndex: "operationDate",
          key: "operationDate",
          width: 140,
        },
        {
          title: "详细",
          dataIndex: "remarks",
          key: "remarks",
          width: 140,
        },
        {
          title: "法务类型",
          dataIndex: "type",
          key: "type",
          width: 140,
        },
        {
          title: "操作时间",
          dataIndex: "createDate",
          key: "createDate",
          width: 140,
        },
        {
          title: "操作",
          dataIndex: "attachmentUrl",
          key: "attachmentUrl",
          width:100,
          render: (text, record) => {
            return (
              <Button
                type="primary"
                disabled={record.name === 0}
                onClick={(attachmentUrl) => {
                  let data = JSON.parse(text);
                  this.setState({
                    visible: true,
                    downloadList: data,
                  });
                  // console.log();
                  // console.log(this.state.downloadList);
                  // if (text) {
                  //   let url = splitUrl(
                  //     text,
                  //     ",",
                  //     globalConfig.avatarHost + "/upload"
                  //   );
                  //   url.forEach((element) => {
                  //     download(element.url);
                  //   });
                  // } else {
                  //   message.info("暂无文件");
                  // }
                  //   console.log(text,record);
                  // e.stopPropagation();
                }}
              >
                {this.state.voucher}
              </Button>
            );
          },
        },
      ],
      visible: false,
      date: "",
      remarks: "",
      mainModalKeys: 0,
      voucher: "下载凭证",
      loading: false,
      downloadList: [],
      visibleLegal: false,
      LegalKeys: 10,
    };
    this.formRef = {};
    this.downloadAll = this.downloadAll.bind(this);
    this.tabelContentRef = null;
    this.addLegal = this.addLegal.bind(this);
    // this.getUrl = this.getUrl.bind(this);
  }

  downloadAll() {
    let list = this.state.downloadList;
    list.forEach((element, key) => {
      // console.log(element);
      setTimeout(() => {
        const a = document.createElement("a");
        a.style.display = "none";
        a.href = `${window.window.globalConfig.context}/open/download?fileName=${element.url}&delete=false&attName=${element.name}`;
        // console.log(a.href);
        document.body.appendChild(a);
        a.click(); // 自动触发点击a标签的click事件
        document.body.removeChild(a);
      }, key * 100);
    });
  }
  onCancel() {
    // console.log(this.state.visible);
  }

  addLegal() {
    let theorgCodeUrl = [];
    if (!this.state.fileList) {
      message.warning("请上传凭证");
      return;
    } else {
      let picArr = [];
      this.state.fileList.map(function (item) {
        if (item.response && item.response.data && item.response.data.length) {
          picArr.push({ name: item.name, url: item.response.data });
        }
      });
      theorgCodeUrl = JSON.stringify(picArr);
      // console.log(theorgCodeUrl);
    }
    if (!this.state.date) {
      message.warning("请选择时间");
      return;
    }
    this.setState({
      addDunOrderLoading: true,
      loading: true,
    });
    $.ajax({
      method: "post",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/lagalAffairs/addLagalAffairsLog",
      data: {
        orderNo: this.props.dataInfor.orderNo,
        type: this.state.type,
        status: this.state.status ? this.state.status : 0,
        date: this.state.date,
        remarks: this.state.remarks,
        attachmentUrl: theorgCodeUrl.length ? theorgCodeUrl : "",
      },
      success: function (data) {
        // console.log(data);
        if (data.error.length) {
          this.setState({
            loading: false,
          });
          message.warning(data.error[0].message);
        } else {
          this.setState({
            loading: false,
            visibleLegal: false,
            LegalKeys: this.state.LegalKeys + 2,
            fileList: undefined,
          });
          // console.log(typeof this.state.type);
          if (this.state.type == "2" || this.state.type == "1") {
            this.props.onFresh();
            this.setState({});
          }
          // this.props.visible = false
          message.success("添加成功");
          this.tabelContentRef && this.tabelContentRef.onRefresh();
          // console.log(this.tabelContentRef);
        }
      }.bind(this),
    }).done(
      function () {
        this.setState({
          addDunOrderLoading: false,
        });
      }.bind(this)
    );
  }
  render() {
    let downloadList = this.state.downloadList;
    const formItemLayout = {
      labelCol: { span: 10 },
      wrapperCol: { span: 12 },
    };
    // console.log(this.props.visibleRest);
    // console.log(this.props.infor);
    return (
      <Modal
        maskClosable={false}
        visible={this.props.visibleRecd}
        onOk={this.props.onCancel}
        onCancel={this.props.onCancel}
        width="1100px"
        title={
          <span
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              paddingRight: "10px",
            }}
          >
            <span>
              <span style={{ marginRight: "5px" }}>法务记录列表</span>
              <Tag color="pink">客户名称：{this.props.dataInfor.buyerName}</Tag>
            </span>
            <Button
              style={{ display: this.props.hid || "inline-block" }}
              type="primary"
              onClick={(e) => {
                e.stopPropagation();
                this.setState({
                  visibleLegal: true,
                });
              }}
            >
              添加法务记录
            </Button>
          </span>
        }
        footer=""
        className="admin-desc-content"
      >
        {/* <TabelContent
          ref={(ref) => (this.tabelContentRef = ref)}
          columns={this.state.columns}
          tabelApi={"/api/admin/lagalAffairs/lagalAffairsLogList"}
          query={{ orderNo: this.props.dataInfor.orderNo }}
          dataProcessing={(data) => {
            // console.log(data.data);
            let theArr = [];
            for (let i = 0; i < data.data.length; i++) {
              let thisdata = data.data[i];
              thisdata.key = i + 1;
              // console.log(thisdata.attachmentUrl);
              // console.log(this.state.voucher);
              if (!thisdata.attachmentUrl) {
                thisdata.name = 0;
              }
              if (thisdata.type == 0) {
                thisdata.type = "法务催收中";
              } else if (thisdata.type == 1) {
                thisdata.type = "延期法务";
              } else if (thisdata.type == 2) {
                thisdata.type = "已坏账处理";
              }
              // console.log(thisdata);
              theArr.push(thisdata);
            }
            return theArr;
          }}
        /> */}
        <TablePopup
          ref={(ref) => (this.tabelContentRef = ref)}
          columns={this.state.columns}
          tabelApi={"/api/admin/lagalAffairs/lagalAffairsLogList"}
          query={{ orderNo: this.props.dataInfor.orderNo }}
          dataProcessing={(data) => {
            // console.log(data.data);
            let theArr = [];
            for (let i = 0; i < data.data.length; i++) {
              let thisdata = data.data[i];
              thisdata.key = i + 1;
              // console.log(thisdata.attachmentUrl);
              // console.log(this.state.voucher);
              if (!thisdata.attachmentUrl) {
                thisdata.name = 0;
              }
              //
              let status;
              if (thisdata.status == 0) {
                status = "否";
              } else if (thisdata.status == 1) {
                status = "已回款";
              } else if (thisdata.status == 2) {
                status = "已诉讼";
              } else if (thisdata.status == 3) {
                status = "已坏账处理";
              }
              //
              if (thisdata.type == 0) {
                thisdata.type = "法务催收中";
              } else if (thisdata.type == 1) {
                thisdata.type = "延期法务";
              } else if (thisdata.type == 2) {
                thisdata.type = `已完成法务/${status}`;
              } else if (thisdata.type == 3) {
                thisdata.type = "自动转交";
              } else if (thisdata.type == 4) {
                thisdata.type = "营销转交";
              }
              // console.log(thisdata);
              theArr.push(thisdata);
            }
            return theArr;
          }}
        />
        <div>
          <Modal
            maskClosable={false}
            visible={this.state.visibleLegal}
            key={this.state.LegalKeys + 2}
            onCancel={() => {
              this.setState({
                visibleLegal: false,
                LegalKeys: this.state.LegalKeys + 2,
              });
            }}
            width="1200px"
            title="新增法务数据"
            footer=""
            className="admin-desc-content"
          >
            <Form
              onSubmit={this.handleSubmit}
              ref={this.formRef}
              style={{ marginRight: "120px" }}
            >
              <Form.Item
                {...formItemLayout}
                label="法务类型"
                name="type"
                hasFeedback
              >
                <RadioGroup
                  onChange={(e) => {
                    this.setState({
                      type: e.target.value,
                    });
                  }}
                >
                  <Radio value="0">法务催收中</Radio>
                  <Radio value="1">延期法务</Radio>
                  <Radio value="2">法务已完成</Radio>
                </RadioGroup>
              </Form.Item>
              {this.state.type == 2 ? (
                <Form.Item
                  {...formItemLayout}
                  label="完成状态"
                  name="status"
                  hasFeedback
                >
                  <RadioGroup
                    onChange={(e) => {
                      this.setState({
                        status: e.target.value,
                      });
                    }}
                  >
                    <Radio value="1">已回款</Radio>
                    <Radio value="2">以诉讼</Radio>
                    <Radio value="3">以坏账处理</Radio>
                  </RadioGroup>
                </Form.Item>
              ) : (
                ""
              )}
              <Form.Item
                name="date"
                {...formItemLayout}
                label="时间"
                hasFeedback
              >
                <DatePicker
                  onChange={(date, dateString) => {
                    this.setState({
                      date: dateString,
                    });
                  }}
                />
              </Form.Item>
              <Form.Item
                name="remarks"
                {...formItemLayout}
                label="法务情况"
                hasFeedback
              >
                <TextArea
                  rows={4}
                  onChange={(e) => {
                    this.setState({
                      remarks: e.target.value,
                    });
                  }}
                />
              </Form.Item>
              <Form.Item
                name="fileList"
                {...formItemLayout}
                label="附件"
                hasFeedback
              >
                <ImgList
                  accept="application/pdf,image/png,application/msword"
                  domId="nowProjectStatus"
                  uploadConfig={{
                    action:
                      globalConfig.context +
                      "/api/admin/newOrder/uploadDunLogFile",
                    data: { sign: "dun_log_attachment" },
                    multiple: true,
                    listType: "text",
                  }}
                  onChange={(info) => {
                    let fileList = info.fileList;
                    this.setState({ fileList });
                  }}
                  fileList={this.state.fileList}
                />
              </Form.Item>
            </Form>
            <div style={{ display: "flex", justifyContent: "center" }}>
              <Button type="primary" loading={this.state.loading}>
                <Popconfirm
                  title="您确定此订单提交法务数据?"
                  onConfirm={this.addLegal}
                  onCancel={() => {
                    this.setState({
                      loading: false,
                    });
                  }}
                  cancelText="取消"
                  okText="确定"
                  loading={this.state.loading}
                >
                  <a href="#">提交</a>
                </Popconfirm>
              </Button>
              <Button
                type="dashed"
                style={{ marginLeft: "15px" }}
                onClick={() => {
                  this.setState({
                    visibleLegal: false,
                    LegalKeys: this.state.LegalKeys + 2,
                  });
                }}
              >
                取消
              </Button>
            </div>
          </Modal>
        </div>
        <Modal
          maskClosable={false}
          visible={this.state.visible}
          onOk={(e) =>
            this.setState({
              visible: false,
            })
          }
          onCancel={(e) =>
            this.setState({
              visible: false,
              mainModalKeys: this.state.mainModalKeys + 1,
              fileList: undefined,
            })
          }
          key={this.state.mainModalKeys}
          width="1200px"
          title="下载凭证"
          footer=""
          className="admin-desc-content"
        >
          <ul style={{ margin: "0 0 10px 0" }}>
            {downloadList.map((item, key) => (
              <li key={key}>
                <span style={{ fontSize: "18px" }}>{item.name}</span>
                <div
                  style={{
                    marginLeft: "10px",
                    color: "#333",
                    display: "inline-block",
                    cursor: "pointer",
                    fontSize: "18px",
                  }}
                  // onClick={() => this.getUrl(item.url, item.name)}
                >
                  <a
                    href={`${window.window.globalConfig.context}/open/download?fileName=${item.url}&delete=false&attName=${item.name}`}
                  >
                    下载附件
                  </a>
                </div>
              </li>
            ))}
          </ul>
          <div style={{ display: "flex", justifyContent: "right" }}>
            <Button
              type="primary"
              onClick={this.downloadAll}
              loading={this.state.loading}
            >
              下载全部
            </Button>
            <Button
              type="dashed"
              style={{ marginLeft: "15px" }}
              onClick={(e) => {
                this.setState({
                  visible: false,
                  mainModalKeys: this.state.mainModalKeys + 1,
                  fileList: undefined,
                });
              }}
            >
              取消
            </Button>
          </div>
        </Modal>
      </Modal>
    );
  }
}

export default LegalRecd;
