<template>
  <div class="app-container form-box" style="padding:20px">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-card class="top15 ">
        <div class="table-card">
          <el-row type="flex" justify="space-around">
            <el-col :span="8"></el-col>
            <el-col :span="8" class="formTitle"> {{title}}</el-col>
            <el-col :span="8" style="text-align: right;padding-right: 20px;">
              <BottomBtn :accessId="accessId" :isAuthorised="isAuthorised" @onConfirm="handleBtTottom" />
            </el-col>
          </el-row>
        </div>
        <div class="table-card table-card-content">
          <el-row>
            <el-col :span="24">
              <el-form-item label="报价编号" prop="number" v-if="$route.query.id">
                <el-input size="small" v-model="form.number" disabled placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="金额" prop="money" size="small" :rules="[{ message: '请输入整数或者保留两位小数', required: false, trigger: 'blur'},{ validator: VerifyFunc.validateMoney }]">
                <el-input placeholder="请输入" :disabled="disabled" v-model="form.money">
                  <div slot="suffix">元</div>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="类别" prop="purchasingCategoriesId" :rules="[{ message: '请选择', required: true, trigger: 'change'}]">
                <el-select v-model="form.purchasingCategoriesId" :disabled="disabled" class="wd100" size="small" placeholder="请选择" filterable>
                  <el-option v-for="it of quotationList" :key="it.id" :value="Number(it.value)" :label="it.label"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品名称" prop="productName" :rules="[{ message: '请输入', required: true, trigger: 'blur'}]">
                <el-input size="small" :disabled="disabled" v-model="form.productName" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="采购名称" prop="projectName" :rules="[{ message: '请输入', required: true, trigger: 'blur'}]">
                <el-input size="small" :disabled="disabled" v-model="form.projectName" placeholder="请输入" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="报价截止时间" prop="cutoffTime">
                <el-date-picker size="small" clearable v-model="form.cutoffTime" class="wd100" :disabled="disabled" type="date" value-format="timestamp" placeholder="选择报价截止时间" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" v-if="!disabled">
              <el-form-item label="供应商" class="op0">
                <el-button plain size="mini" icon="el-icon-plus" @click="handleAddSp">添加供应商</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="供应商信息列表" required>
                <el-table stripe border :data="form.supplierList" ref="supplierList">
                  <el-table-column label="企业名称" align="center" prop="companyAme" />
                  <el-table-column label="供应商编码" align="center" prop="companyNumber" />
                  <el-table-column label="企业性质" align="center" prop="companyType">
                    <template v-slot="scope">
                      <dict-tag :type="DICT_TYPE.BS_ENTERPRISEL_TYPE" :value="scope.row.companyType" />
                    </template>
                  </el-table-column>
                  <el-table-column label="法人代表" align="center" prop="legalPerson" />
                  <el-table-column label="联系方式" align="center" prop="phone" />
                  <el-table-column label="统一社会信用代码" align="center" prop="creditCode" />
                  <el-table-column label="银行户名" align="center" prop="bankName" />
                  <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                    <template v-slot="scope">
                      <span>{{ parseTime(scope.row.createTime) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" v-if="!disabled">
                    <template v-slot="scope">
                      <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row,1)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" v-if="!disabled">
              <el-form-item label="物料信息" class="op0">
                <el-button plain size="mini" icon="el-icon-plus" @click="handleAddQuo">关联物料</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="物料信息列表" required>
                <el-form :rules="qusRules" ref="qusForm">
                  <el-table stripe border :data="form.quotationDetails" ref="quotationDetails">
                    <el-table-column label="物料名称" align="center" prop="materielName" />
                    <el-table-column label="物料编码" align="center" prop="materielCode" />
                    <el-table-column align="center" prop="descStr">
                      <template slot="header">
                        <span style="color: #ff4949;margin-right: 2px;">*</span> 规格描述
                      </template>
                      <template v-slot="scope">
                        <el-input size="small" :disabled="disabled" v-model="scope.row.descStr" placeholder="请输入" />
                      </template>
                    </el-table-column>
                    <el-table-column label="单台用量" align="center" prop="dosage">
                      <template v-slot="scope">
                        <el-input size="small" :disabled="disabled" v-model="scope.row.dosage" placeholder="请输入" />
                      </template>
                    </el-table-column>
                    <el-table-column label="单位" align="center" prop="unit">
                      <template v-slot="scope">
                        <el-input size="small" :disabled="disabled" v-model="scope.row.unit" placeholder="请输入" />
                      </template>
                    </el-table-column>
                    <el-table-column label="材质" align="center" prop="quality">
                      <template v-slot="scope">
                        <el-input size="small" :disabled="disabled" v-model="scope.row.quality" placeholder="请输入" />
                      </template>
                    </el-table-column>
                    <el-table-column label="备注" align="center" prop="remark">
                      <template v-slot="scope">
                        <el-input size="small" :disabled="disabled" :autosize="{ minRows: 1, maxRows: 1}" v-model="scope.row.remark" type="textarea" placeholder="请输入" />
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" v-if="!disabled">
                      <template v-slot="scope">
                        <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row,2)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="附件">
                <UploadFile @onUploadFile="handleUpload" :files="fileList" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </el-form>
    <el-image-viewer v-if="dialogVisible" :zIndex="9999" :on-close="closeImgViewer" :url-list="imgList" />
    <!-- 打印信息 -->
    <el-dialog :visible.sync="showPrintPage" width='1200px' custom-class="print-dialog" style="height: 98vh;overflow-y: auto;">
      <div style="text-align: right;margin-bottom:10px;">
        <el-button @click="PrintRow" type='primary' size='mini' plain>确认打印</el-button>
      </div>
      <div id="printMe" ref="print" class="print-main">
        <print-html :infoForm='form' :dialogTitle="'报价单'" :quotationList="quotationList" :tasks="tasks" />
      </div>
    </el-dialog>
    <!-- 审批流程信息 -->
    <FlowDialog ref="FlowDialog" :isOpen="showFlow" @onCancel="showFlow = false" @onSetId="handleSetApprovalId" @onTasks="handleTasks" :processInstanceId="form.processInstanceId" />
    <!-- 展示供应商信息 -->
    <ListDialog :isOpen="isOpen" @onCancel="isOpen = false" :selectIds="form.supplierIdList" @onConfirm="handleConfirm" />
    <!-- 展示物料信息 -->
    <QuoListDialog @onConfirm="handleQsConfirm" :selectIds="form.quotationDetails.map(item=>item.id)" :isOpen="isQsOpen" @onCancel="isQsOpen = false" />
  </div>
</template>

<script>
import { debounce } from 'lodash'
import dayjs from "dayjs";
import { listData } from "@/api/system/dict/data";
import { createQuotationSheet, updateQuotationSheet, deleteQuotationSheet, getQuotationSheet, getQuotationSheetPage, exportQuotationSheetExcel } from "@/api/bs/quotationSheet";
import VerifyFunc from "@/utils/verity";

export default {
  name: 'supplierTb',
  components: {
    printHtml: () => import('./printHtml'),
    ListDialog: () => import('../../components/ListDialog'),
    QuoListDialog: () => import('./quoListDialog'),
    FilePreview: () => import('@/components/FilePreview'),
    CommonName: () => import('@/components/CommonName'),
    FlowDialog: () => import('@/components/FlowDialog'),
    BottomBtn: () => import('@/components/BottomBtn'),
    UploadFile: () => import('@/components/UploadFile'),
    InputSelect: () => import('@/components/InputSelect'),
    // List: () => import('../../../components/TogetherList'),
    // printHtml: () => import('./printHtml'),
  },
  created() {
    if (this.$route.query.id) {
      this.handleInitForm(this.$route.query.id)
    }
    this.handleInitList()
  },
  watch: {
    fileList: {
      immediate: true,
      deep: true,
      handler(val) {
        if (val.length >= 1) {
          this.hideUpload = true
        } else {
          this.hideUpload = false
        }
      }
    }
  },
  computed: {
    disabled() {
      return !['add', 'edit'].includes(this.$route.query.flag)
    },
    title() {
      return this.$route.query.title
    },
    isShow() {

    },
  },
  data() {
    return {
      qusRules: {
        materielName: [
          { required: true, message: "请输入", trigger: "blur" }
        ]
      }, // 物料规则
      qsTableList: [], // 物料信息列表
      isQsOpen: false,
      spTitle: '请选择',
      isOpen: false,
      isAuthorised: false,
      accessId: null,
      tasks: {},
      showFlow: false,
      showPrintPage: false,
      selectUserIds: [],
      VerifyFunc,
      defaultProps: {
        children: "children",
        label: "name",
        value: 'id',
        checkStrictly: false
      },
      areaTree: [],
      previewFile: false,
      fileUrl: null,
      mode: null,
      selectIds: [],
      lsIsOpen: false,
      tgIsOpen: false,
      addressList: [],
      tripTypeList: [],
      pdfName: null,
      isPdf: false,
      imgType: '.jpeg, .jpg, .png, .pdf',
      fileList: [],
      hideUpload: false,
      imgList: [], //当前图片src数组
      dialogVisible: false,
      prviewUrl: null,
      form: {
        materialIdList: [],
        quotationDetails: [],
        supplierList: [],
        supplierIdList: [],
      },
      quotationList: [],
      // 表单校验
      rules: {
        reason: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      userList: [],
      index: 0
    }
  },
  methods: {
    handleQsConfirm(list) {
      let arr = this.form.quotationDetails
      list.forEach(n => { arr.push(n) })
      this.$set(this.form, 'quotationDetails', arr)
      this.$set(this.form, 'materialIdList', (arr || []).map(item => item.id))
      this.isQsOpen = false
    },
    handleDelete(row, type) {
      if (type === 1) {
        this.form.supplierList = this.form.supplierList.filter(item => item.id !== row.id) || []
        this.form.supplierIdList = this.form.supplierIdList.filter(item => item !== row.id) || []

      } else {
        this.form.quotationDetails = this.form.quotationDetails.filter(item => item.id !== row.id) || []
        this.form.materialIdList = this.form.materialIdList.filter(item => item !== row.id) || []
      }
    },
    handleFilterExtendList(list) {
      let str = '-'
      let arr = []
      if (Array.isArray(list) && list.length) {
        list.forEach(n => {
          arr.push(`${n.key}:${n.name}`)
        })
      }
      str = arr.join('、') || '-'
      return str
    },
    handleAddQuo() {
      this.isQsOpen = true
    },
    handleAddSp() {
      this.isOpen = true
    },
    handleConfirm(list) {
      let arr = this.form.supplierList
      list.forEach(n => { arr.push(n) })
      this.$set(this.form, 'supplierList', arr)
      this.$set(this.form, 'supplierIdList', (arr || []).map(item => item.id))
      this.isOpen = false
    },
    handleCancel() {
      this.isOpen = false
    },
    handleShow() {
      this.isOpen = true
      console.log('demo..');
    },
    handleSetApprovalId(id) {
      this.accessId = id
    },
    handleUpload(list) {
      this.fileList = list
    },
    handleBtTottom(val) {
      if (val === 0 || val === 1) {
        this.submitForm(val)
      } else if (val == 2) {
        this.showPrintPage = true
      } else {
        this.showFlow = true
      }
    },
    handleTasks(tasks) {
      this.tasks = tasks
    },
    PrintRow: debounce(function () { //确认打印档案
      this.$print(this.$refs.print)
    }, 200),
    handlePrint() {
      this.showPrintPage = true
    },
    handleLoop(array) {
      array.forEach(el => {
        if (el.children && !el.children.length) {
          delete el.children
        } else {
          this.handleLoop(el.children)
        }
      });
    },
    handleInitList() {
      // 获取类别
      listData({
        pageNo: 1,
        pageSize: 100,
        dictType: 'material_type',
      }).then((res) => {
        this.quotationList = res.data.list || []
      })
    },
    handleTimeChange(val, index) {
      let startTime = dayjs(val[0]).format('YYYY/MM/DD 00:00:00')
      let endTime = dayjs(val[1]).format('YYYY/MM/DD 23:59:59')
      this.$set(this.form.expenseApplyTrips[index], 'startTime', startTime)
      this.$set(this.form.expenseApplyTrips[index], 'endTime', endTime)
    },
    handleInitForm(id) {
      this.processInstanceLoading = true
      getQuotationSheet(id).then(response => {
        this.form = response.data || {};

        this.form = {
          ...this.form,
        }
        // if (this.$route.query.typeStr === 'business') {
        //   this.form.expenseApplyTrips = this.form.expenseApplyTrips.map((item) => {
        //     return {
        //       ...item,
        //       departureLocation: Number(item.departureLocation),
        //       destinationLocation: Number(item.destinationLocation),
        //       tripType: Number(item.tripType),
        //       amount: item.amount ? item.amount : undefined,
        //       time: [new Date(dayjs(item.startTime).format('YYYY/MM/DD')), new Date(dayjs(item.endTime).format('YYYY/MM/DD'))]
        //     }
        //   })
        // }
        this.fileList = this.form.files || []
        this.$nextTick(() => {
          this.form.processInstanceId && this.$refs.FlowDialog.getDetail(this.form.processInstanceId)
        })
        this.isAuthorised = this.form.isAuthorised
      });
    },
    submitForm(type) {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }

        // 判断供应商是否选择
        if (!this.form.supplierList.length) {
          return this.$modal.msgWarning(`请选择供应商！`);
        }
        //  判断物料信息是否满足条件
        let array = this.form.quotationDetails
        if (array.length) {
          const isValid1 = array.every(item => {
            return item.descStr;
          });
          if (!isValid1) {
            return this.$modal.msgWarning(`请输入规则描述！`);
          }
          let regex = /^[1-9]\d*$/;
          const isValid2 = array.every(item => {
            if (item.dosage) {
              return regex.test(Number(item.dosage));
            }
          });
          if (!isValid2) {
            return this.$modal.msgWarning(`单台用量格式错误！`);
          }
        } else {
          return this.$modal.msgWarning(`请关联物料信息！`);
        }

        // 添加/修改的提交
        let newForm = {
          ...this.form,
          quotationDetails: this.form.quotationDetails.map(item => {
            return {
              ...item,
              materialId: this.form.id ? item.materialId : item.id,
              id: this.form.id ? item.id : null
            }
          }),
          supplierIdList: this.form.supplierList.map(item => item.id),
          status: type,
          type: this.$route.query.typeStr == 'in' ? 1 : 2,
          files: this.fileList,
        }


        if (newForm.id) {
          updateQuotationSheet(newForm).then(response => {
            this.$modal.msgSuccess(`修改成功!`);
            history.back()
          });
        } else {
          createQuotationSheet(newForm).then(response => {
            this.$modal.msgSuccess(`新增成功!`);
            history.back()
          });

        }
      });
    },
    cancel() {
      this.$emit('onCancel')
    },
  }
}
</script>
<style lang="scss" scoped>
@import '@/assets/styles/form/index.scss';
.my-process-designer {
  background: #fff !important;
}
</style>