<template>
  <div>
    <xy-dialog
      ref="dialog"
      :is-show.sync="isShow"
      type="form"
      :title="type === 'add' ? '新增合同事项' : '编辑合同事项'"
      :form="form"
      :rules="rules"
      @submit="submit"
    >
      <template #extraFormTop v-if="false">
        <el-form-item size="small">
          <div class="xy-table-item">
            <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
            >是否需要签订合同</span
            >
            </div>
            <div class="xy-table-item-content">
              <el-switch
                disabled
                :value="true"
                active-text="是"
                inactive-text="否"
                style="width: 300px"
              />
            </div>
          </div>
        </el-form-item>
      </template>
      <template v-slot:name>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
            >*</span
            >项目名称
          </div>
          <div class="xy-table-item-content">
            <el-input
              v-model="form.name"
              @change="checkName"
              placeholder="请填写项目名称"
              style="width: 300px"
            />
          </div>
        </div>
      </template>
      <template #contract_type>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            合同类型
          </div>
          <div class="xy-table-item-content">
            <el-select v-model="form.contract_type" style="width: 300px">
              <el-option v-for="(item,index) in ['收入类','支出类','技术协议']" :label="item" :value="index+1"></el-option>
            </el-select>
          </div>
        </div>
      </template>
      <!--<template v-slot:number>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>合同编号
          </div>
          <div class="xy-table-item-content">
            <el-input placeholder="请填写合同编号" v-model="form.number" style="width: 300px;" />
          </div>
        </div>
      </template>-->
      <template v-slot:supply>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>承包商\供应商
          </div>
          <div class="xy-table-item-content">
            <el-input placeholder="请填写承包商\供应商" v-model="form.supply" style="width: 300px;" />
          </div>
        </div>
      </template>
      <template v-slot:money>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>合同金额
          </div>
          <div class="xy-table-item-content xy-table-item-price">
            <el-input-number :controls="false" :precision="2" placeholder="请填写合同金额" v-model="form.money" style="width: 300px;" />
          </div>
        </div>
      </template>
      <!--
      <template v-slot:guarantee_money>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>质保金
          </div>
          <div class="xy-table-item-content xy-table-item-price">
            <el-input-number :precision="2" :controls="false" placeholder="请填写质保金" v-model="form.guarantee_money"
                             style="width: 300px;" />
          </div>
        </div>
      </template>
      <template v-slot:start_date>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>合同服务时间
          </div>
          <div class="xy-table-item-content">
            <el-date-picker style="width: 300px;" value-format="yyyy-MM-dd" v-model="time" type="daterange"
                            range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                            @change="e => {
                              (e[0] && e[1]) ?
                                (form.start_date = e[0],
                                form.end_date = e[1])
                                : (form.start_date = '',form.end_date = '')

                            }">
            </el-date-picker>
          </div>
        </div>
      </template>
      <template v-slot:guarantee_year>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>质保期
          </div>
          <div class="xy-table-item-content xy-table-item-year">
            <el-input-number :controls="false" placeholder="请填写质保期" v-model="form.guarantee_year"
                             style="width: 300px;" />
          </div>
        </div>
      </template>
      <template v-slot:date>
        <div class="xy-table-item">
          <div class="xy-table-item-label">

            <span style="color: red;">*</span>
            签订日期
          </div>
          <div class="xy-table-item-content">
            <el-date-picker style="width: 300px;" value-format="yyyy-MM-dd" v-model="form.date" type="date">
            </el-date-picker>
          </div>
        </div>
      </template>-->
      <template v-slot:is_framework>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
            >*</span
            >是否框架协议
          </div>
          <div class="xy-table-item-content">
            <el-switch
              v-model="form.is_framework"
              active-text="是"
              inactive-text="否"
              :active-value="1"
              :inactive-value="0"
            />
          </div>
        </div>
      </template>
      <!--
      <template v-slot:files>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
            >*</span
            >文件 ：
          </div>
          <div class="xy-table-item-content">
            <el-upload
              style="width: 300px"
              ref="upload"
              multiple
              :on-success="successHandle"
              :before-upload="uploadBefore"
              accept=".rar,.zip,.doc,.docx,.pdf,.jpg,.png,.gif,.xls,.xlsx"
              :action="action"
              :file-list="fileLists"
              :auto-upload="false"
              :on-remove="removeHande"
              :limit="100"
            >
              <el-button slot="trigger" size="small" type="primary"
              >选取文件</el-button
              >
              <el-button
                style="margin-left: 10px"
                size="small"
                type="success"
                @click="$refs['upload'].submit()"
              >开始上传</el-button
              >
              <div slot="tip" class="el-upload__tip">
                支持文件格式：.rar .zip .doc .docx .pdf .jpg .png .gif .xls
                .xlsx
                <br />单个文件不能超过20M
              </div>
            </el-upload>
          </div>
        </div>
      </template>
      -->
    </xy-dialog>
  </div>
</template>

<script>
import {
  detailContract as show,
  editorContract as save,
  addContrant as store,
  checkContractName
} from '@/api/contract/contract'
export default {
  props: {
  },
  data() {
    return {
      isShow: false,
      id: "",
      type: "",
      action: process.env.VUE_APP_UPLOAD_API,
      file_ids: [],

      time: [],
      form: {
        name: "",
        contract_type: 1,
        number: "",
        supply: "",
        money: "",
        start_date: "",
        end_date: "",
        guarantee_money: "",
        guarantee_year: "",
        date: this.$moment().format('YYYY-MM-DD'),
        is_contract: 1,
        is_framework: "",
        purchase_status: 3,
        //join_status: 3,
        invite_status: 3,
        files: []
      },
      fileLists: [],
      rules: {
        name: [
          {
            required: true,
            message: "请填写合同名称",
          },
        ],
        number: [
          {
            required: true,
            message: "请填写合同编号",
          },
        ],
        money: [
          {
            required: true,
            message: "请填写合同金额",
          },
        ],
        guarantee_money: [
          {
            required: true,
            message: "请填写保证金",
          },
        ],
        guarantee_year: [
          {
            required: true,
            message: "请填写保证期",
          },
        ],
        date: [
          {
            required: true,
            message: "请填写签订日期",
          },
        ],
      },
    };
  },
  methods: {
    show() {
      this.isShow = true;
    },
    hidden() {
      this.isShow = false;
    },
    init() {
      for (let key in this.form) {
        if (this.form[key] instanceof Array) {
          this.form[key] = [];
        } else {
          this.form[key] = "";
        }
      }
      this.$refs["dialog"].clearValidate();
    },
    setId(id) {
      if (typeof id == "number") {
        this.id = id;
      } else {
        console.error("error typeof id: " + typeof id);
      }
    },
    getId() {
      return this.id;
    },
    setType(type = "add") {
      let types = ["add", "editor"];
      if (types.includes(type)) {
        this.type = type;
      } else {
        console.warn("Unknown type: " + type);
      }
    },
    setForm(key = [], value = []) {
      if (key instanceof Array) {
        key.forEach((key, index) => {
          this.form[key] = value[index] ?? "";
        });
      }
      if (typeof key === "string") {
        this.form[key] = value;
      }
      if (!key) {
        this.init();
      }
    },

    //上传
    successHandle(response, file, fileList) {
      this.fileLists = fileList;
    },
    removeHande(file, fileList) {
      this.fileLists = fileList;
    },
    uploadBefore(file) {
      console.log(file);
      if (file.size / 1000 > 20 * 1024) {
        this.$message({
          type: "warning",
          message: "上传图片大小超过20MB！",
        });
        return false;
      }
    },

    async getDetail() {
      const res = await show({ id: this.id });
      this.$integrateData(this.form, res);
      if (this.form.start_date && this.form.end_date) this.time = [this.form.start_date,this.form.end_date]
      this.fileLists = res.files_detail.map(i => ({
        name: i.original_name,
        url: i.url,
        response: i
      }))
    },

    submit() {
      if (this.type === "add") {
        if (this.form.hasOwnProperty("id")) {
          delete this.form.id;
        }
        store(this.form).then((res) => {
          this.$message({
            type: "success",
            message: "新增合同",
          });
          this.isShow = false;
          this.$emit("refresh");
        })
      }
      this.form.files = this.fileLists.map(i => i.response?.id)
      if (this.type === "editor") {
        Object.defineProperty(this.form, "id", {
          value: this.id,
          enumerable: true,
          configurable: true,
          writable: true,
        });
        save(this.form).then((res) => {
          this.$message({
            type: "success",
            message: "编辑合同",
          });
          this.isShow = false;
          this.$emit("refresh");
        });
      }
    },
    //y验证合同的名称是否存在重复
    checkName(e) {
      checkContractName({ name: e }).then((res) => {
        console.log(res);
      });
    },
  },
  watch: {
    isShow(val) {
      if (val) {
        if (this.type === "editor") {
          this.getDetail();
        }
      } else {
        this.id = "";
        this.type = "";
        this.init();
        this.$refs["dialog"].clearValidate();
        delete this.form.id;
      }
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-input__inner {
  text-align: left;
}
</style>
