<template>
  <div>
    <Row style="marginTop:10px">
      <Col :span="24">
        <Card>
          <!-- <p slot="title">
          编辑收款信息(<span style="color:red;">*</span>为必输字段)
          </p>-->

          <div>
            <Form :model="editForm" ref="editForm" :rules="rules" :label-width="120" inline>
              <Form-item prop="compCode" v-show="false">
                <input type="hidden" v-model="editForm.compCode" :disabled="readonly">
              </Form-item>
              <Form-item prop="currencyName" v-show="false">
                <input type="hidden" v-model="editForm.currencyName" :disabled="readonly">
              </Form-item>
              <Form-item prop="paymentTypeName" v-show="false">
                <input type="hidden" v-model="editForm.paymentTypeName" :disabled="readonly">
              </Form-item>
              <Form-item prop="date" v-show="false">
                <input type="hidden" v-model="editForm.date" :disabled="readonly">
              </Form-item>
              <Row>
                <Col :span="12">
                  <Form-item prop="compName" label="收款单位">
                    <SelectCompCode
                      title="请选择收款单位"
                      v-model="editForm.compName"
                      @handleSelect="select_compCode"
                      :disabled="readonly"
                    ></SelectCompCode>
                  </Form-item>
                </Col>
                <Col :span="12">
                  <Form-item prop="receivablesBankNum" label="收款账号">
                    <SelectCompCode
                      title="请选择收款单位"
                      v-model="editForm.receivablesBankNum"
                      @handleSelect="select_compCode"
                      :disabled="readonly"
                    ></SelectCompCode>
                  </Form-item>
                </Col>
              </Row>
              <Row>
                <Col :span="12">
                  <Form-item prop="paymentCompName" label="付款单位">
                    <Input
                      v-model="editForm.paymentCompName"
                      type="text"
                      :clearable="!readonly"
                      :disabled="readonly"
                    />
                  </Form-item>
                </Col>
                <Col :span="12">
                  <Form-item prop="paymentBankNum" label="付款账号">
                    <Input
                      v-model="editForm.paymentBankNum"
                      type="text"
                      :clearable="!readonly"
                      :disabled="readonly"
                    />
                  </Form-item>
                </Col>
              </Row>
              <Row>
                <Col :span="12">
                  <Form-item prop="receivablesAmount" label="收款金额">
                    <Input
                      :number="true"
                      v-model="editForm.receivablesAmount"
                      type="text"
                      :clearable="!readonly"
                      :disabled="readonly"
                    />
                  </Form-item>
                </Col>
                <Col :span="12">
                  <Form-item prop="receivablesDate" label="收款日期">
                    <DatePicker
                      @on-change="change_date"
                      :options="receivablesDateOption"
                      v-model="editForm.date"
                      placeholder="请选择日期"
                      type="date"
                      format="yyyy-MM-dd"
                      :clearable="!readonly"
                      :editable="false"
                      :disabled="readonly"
                    ></DatePicker>
                  </Form-item>
                </Col>
              </Row>
              <Row>
                <Col :span="12">
                  <Form-item prop="currencyCode" label="收款币种">
                    <DataSelect
                      v-model="editForm.currencyCode"
                      code="currency"
                      @on-change="change_currencyName"
                      :label-in-value="true"
                      :clearable="!readonly"
                      :disabled="readonly"
                    ></DataSelect>
                  </Form-item>
                </Col>
                <Col :span="12">
                  <!-- <Form-item prop="serviceCharge" label="手续费">
                <Input :number="true" v-model="editForm.serviceCharge" type="text"/>
                  </Form-item>-->
                  <Form-item prop="paymentTypeCode" label="收款方式">
                    <DataSelect
                      :filterValue="['1','2','5']"
                      style="width:100px;"
                      v-model="editForm.paymentTypeCode"
                      code="ReceivablesPaymentType"
                      @on-change="change_paymentTypeName"
                      :label-in-value="true"
                      :clearable="!readonly"
                      :disabled="readonly"
                    ></DataSelect>
                  </Form-item>
                </Col>
              </Row>
              <Row>
                <Col :span="12" v-if="isBankSerialNumber">
                  <Form-item prop="bankSerialNumber" label="流水号">
                    <Input
                      v-model="editForm.bankSerialNumber"
                      type="text"
                      maxlength="50"
                      :clearable="!readonly"
                      :disabled="readonly"
                    />
                  </Form-item>
                </Col>
                <Col :span="12" v-if="!isBankSerialNumber">
                  <Form-item label="流水号">
                    <Input
                      v-model="editForm.bankSerialNumber"
                      type="text"
                      maxlength="50"
                      :clearable="!readonly"
                      :disabled="readonly"
                    />
                  </Form-item>
                </Col>
                <Col :span="12">
                  <Form-item label=" ">
                    <Button type="warning" @click="relatedImagesHandle" v-if="!readonly">
                      <Icon type="link"></Icon> 关联影像
                    </Button>
                    
                    <Button type="warning" @click="imagerReadingUrlVO" v-if="readonly">
                      <Icon type="link"></Icon> 查看影像
                    </Button>

                    <Button v-if="!!detail" class="red">已关联（{{detail.imageCount || 0}}）张</Button>
                  </Form-item>
                </Col>
              </Row>
              <Row>
                <Col>
                  <Card>
                    <p slot="title">关联附件</p>
                    <UploadFile
                      @inputData="uploadFilesHandle"
                      :ids="editForm.fileIds"
                      :closeBtn="false"
                      :uploadBtn="!readonly"
                      :fileNum="detail && detail.receivablesNum"
                    ></UploadFile>
                  </Card>
                </Col>
              </Row>
            </Form>
          </div>
        </Card>
      </Col>
    </Row>
  </div>
</template>

<script>
import UploadFile from "../receivablesClaim/components/file/uploadFile.vue";
import { DataSelect } from "ems-components";
import miment from "miment";
import Server from "./server.js";
import util from "@/tools/util.js";
import { SelectCompCode } from "ems-receivable@/components/index.js";
const server = new Server();
export default {
  name: "ManuallyAddEditPage",
  components: {
    DataSelect,
    SelectCompCode,
    UploadFile
  },
  props: {
    detail: {
      type: Object,
      default: null
    },
    readonly: {
      type: Boolean,
      default: false
    }
  },
  data() {
    // const serviceChargeValid = (rule, value, callback) => {
    //   if (value === "") {
    //     callback();
    //   } else if(+value >= 0 ) {
    //     callback();
    //   }else{
    //     if(+value < 0){
    //       callback(new Error('不能为负数'));
    //     }else if(isNaN(value)){
    //       callback(new Error('输入的值不正确'));
    //     }else{
    //       callback();
    //     }
    //   }
    // };
    const receivablesAmountValid = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入收款金额"));
      } else if (+value < 0) {
        callback(new Error("不能为负数"));
      } else if (isNaN(value)) {
        callback(new Error("输入的值不正确"));
      } else {
        callback();
      }
    };
    return {
      isBankSerialNumber: false, //流水号是否必填
      server: server,
      editForm: {
        compCode: "", //收款单位code
        compName: "", //收款单位名称
        receivablesBankNum: "", //收款账号
        paymentCompName: "", //付款单位名称
        paymentBankNum: "", //付款账号
        //serviceCharge: "", //手续费，保留两位小数
        currencyCode: "CNY", //收款币种编码
        currencyName: "人民币", //收款币种名称
        paymentTypeCode: "", //收款方式编码
        paymentTypeName: "", //收款方式名称
        receivablesAmount: "", //收款金额，保留两位小数
        date: "", //收款日期 Date 类型
        receivablesDate: null, //收款日期，格式为“2018-12-12”
        // receivablesId:"",//收款信息主键，新增不传，修改传
        operatingStatus: "1", //操作方式 1新增 2修改
        bankSerialNumber: "", //流水号
        fileIds: ""
      },
      // 收款日期 不允许选择未来时间
      receivablesDateOption: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now();
        }
      },
      receivablesNum: "",
      //验证规则
      rules: {
        compName: [
          {
            required: true,
            message: "请选择收款单位!",
            trigger: "change"
          }
        ],
        receivablesBankNum: [
          {
            required: true,
            message: "请选择收款账号!",
            trigger: "change"
          }
        ],
        paymentCompName: [
          {
            required: true,
            message: "请输入付款单位!",
            trigger: "blur"
          }
        ],
        // 乐见：付款账号非必需 20190704V
        // paymentBankNum: [
        //   {
        //     required: true,
        //     message: "请输入付款单位账号!",
        //     trigger: "blur"
        //   }
        // ],
        currencyCode: [
          {
            required: true,
            message: "请选择收款币种!",
            trigger: "blur"
          }
        ],
        paymentTypeCode: [
          {
            required: true,
            message: "请选择收款方式!",
            trigger: "blur"
          }
        ],
        receivablesAmount: [
          {
            type: "number",
            required: true,
            trigger: "blur",
            validator: receivablesAmountValid
          }
        ],
        // serviceCharge: [
        //   {
        //     type: "number",
        //     required: false,
        //     validator: serviceChargeValid,
        //     trigger: "blur"
        //   }
        // ],
        receivablesDate: [
          {
            required: true,
            message: "请选择收款日期!",
            trigger: "change"
          }
        ],
        bankSerialNumber: [
          {
            required: true,
            message: "请填写流水号!",
            trigger: "blur"
          }
        ]
      }
    };
  },
  async created() {
    if (this.readonly) {
      this.$emit("SetTitle", "查看收款信息");
    } else {
      this.$emit("SetTitle", this.detail ? "编辑收款信息" : "新增收款信息");
    }

    //当前页 “保存”按钮配置

    if (!this.readonly) {
      this.$emit("SetPageActions", [
        {
          text: "保存",
          theme: "warning",
          icon: "edit",
          action: "save",
          handle: this.save
        },
        {
          text: "重置",
          theme: "info",
          // icon: "edit",
          action: "reset",
          handle: this.reset
        }
      ]);
    }

    if (this.detail) {
      this.editForm = Object.assign({}, this.editForm, this.detail);
      this.editForm.date = new Date(this.detail.receivablesDate);
      this.editForm["operatingStatus"] = "2"; //修改
      if (this.editForm.paymentTypeCode == "2") {
        this.isBankSerialNumber = true;
      } else {
        this.isBankSerialNumber = false;
      }
    } else {
      this.editForm["operatingStatus"] = "1"; //新增
    }
  },
  beforeMount: function() {},
  mounted: function() {},
  beforeDestroy: function() {},
  destroyed: function() {},
  methods: {
    uploadFilesHandle(ids) {
      debugger;
      this.editForm.fileIds = ids;
    },
    clear_compCode() {
      this.editForm.compCode = "";
      this.editForm.compName = "";
      this.editForm.receivablesBankNum = "";
    },
    select_compCode(data) {
      if (!data) return this.clear_compCode();
      this.editForm.compCode = data.compCode;
      this.editForm.compName = data.compName;
      this.editForm.receivablesBankNum = data.bankAccountNum;
    },
    //设置日期为字符串格式的值
    change_date(data, type) {
      this.editForm.receivablesDate = data || "";
    },
    //选择币种
    change_currencyName(data) {
      this.editForm.currencyName = data ? data.label : "";
    },
    //选择收款方式
    change_paymentTypeName(data) {
      this.editForm.paymentTypeName = data ? data.label : "";
      this.editForm.bankSerialNumber = "";
      if (this.editForm.paymentTypeCode == "2") {
        this.isBankSerialNumber = true;
      } else {
        this.isBankSerialNumber = false;
      }
    },
    //保存
    save(cb) {
      if (this.editForm.paymentTypeCode != "2") {
        this.rules.bankSerialNumber = [];
      } else {
        this.rules.bankSerialNumber = [
          {
            required: true,
            message: "请填写流水号!",
            trigger: "blur"
          }
        ];
      }
      // 苏乐见 : 前端取消必填校验，后端进行校验。
      // if (!this.editForm.fileIds) {
      //   return this.$Message.error("请上传附件后再保存！");
      // }
      this.$refs["editForm"].validate(async valid => {
        if (valid) {
          this.$emit("SetActionsState", { btn: "save", state: true });
          let msg = this.detail ? "更新收款信息成功" : "新增收款信息成功";
          let result = await this.server.edit(this.editForm);
          this.$emit("SetActionsState", { btn: "save", state: false });
          if (result.statusCode === "-1") {
            this.$Message.error(result.msg);
          } else {
            this.$Message.success(msg);
            this.editForm["operatingStatus"] = "2";
            !cb && this.$emit("Close", true);
            cb && cb(result);
          }
        }
      });
    },
    reset() {
      this.$refs["editForm"].resetFields();
    },
    openImageLink(receivablesNum){
      server.imageObtainUrl({ receivablesNum }).then(res => {
        if(res.data){
          util.openLink(res.data);
        }else{
          this.$Message.error(res.message)
        }
      });
    },
    relatedImagesHandle() {
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          if (this.detail && this.detail.receivablesNum) {
            const receivablesNum = this.detail.receivablesNum;
            this.openImageLink(receivablesNum)
          } else if (this.receivablesNum){
            this.openImageLink(this.receivablesNum)
          } else {
            this.save(result => {
              const receivablesNum = result.data.data.receivablesNum;
              this.receivablesNum = receivablesNum
              this.openImageLink(receivablesNum)
            });
          }
        } else {
          this.$Message.error("请先填写必填项再关联！");
        }
      });
    },
    imagerReadingUrlVO() {
      if (this.detail && this.detail.receivablesNum) {
        server.imagerReadingUrlVO({ receivablesNum: this.detail.receivablesNum }).then(res => {
          util.openLink(res.data);
        });
      }
    }
  },
  watch: {},
  directives: {}
};
</script>
