<template>
  <div class="mold-header table_90 f-12">
    <el-row>
      <!--表单-->
      <el-form :inline="true" :model="formInline" :rules="rules" class="demo-form-inline">
        <el-row :gutter="10">
          <el-col :span="12" v-if="formInline.dotype != 'add'">
            <el-form-item label="模具编号" label-width="78px" prop="number">{{ formInline.matrix_sn }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模具名称" prop="matrix_title">
              <el-input v-model="formInline.matrix_title" placeholder="模具名称" maxlength="255"
                style="width: 480px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-row>
    <!--表格-->
    <div class="table_90 f-12">
      <h2>
        模具关联半成品管理
        <span style="font-size: 0.5em; font-weight: 500">（此处只关联直接由模具生产的物料信息）</span>
      </h2>

      <vxe-table border :data="tableColumn" style="margin-top: 15px" ref="xTable"
        :edit-config="{ trigger: 'click', mode: 'row' }" row-id="keyid" :edit-rules="rules">
        <vxe-column field="produce_sn" title="半成品物料编码" :edit-render="{}" prop="produce_sn">
          <template #edit="{ row }">
            <vxe-input v-model="row.produce_sn" @blur="getMaterial(row.produce_sn, row.keyid)" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="id" title="id" :visible="false"></vxe-column>
        <vxe-column field="produce_titile" title="半成品物料名称"></vxe-column>
        <vxe-column field="produce_sku" title="半成品物料规格型号（sku）"></vxe-column>
        <vxe-column field="holes_num" title="模具穴数" :edit-render="{}" prop="holes_num">
          <template #edit="{ row }">
            <vxe-input v-model.number="row.holes_num" @blur="getHolesNum(row.holes_num, row.keyid, 1)" type="text"
              maxlength="7"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="capacity_num" title="模具产能（每小时）" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-input v-model="row.capacity_num" @blur="getHolesNum(row.capacity_num, row.keyid, 2)" type="text"
              maxlength="7"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="operation" title="操作" width="100">
          <template #default="{ row }">
            <el-button size="mini" @click="removeRow(row)" status="danger">删除行</el-button>
          </template>
        </vxe-column>
      </vxe-table>
      <vxe-button @click="insertEvent(-1)" class="mold-header" status="primary">新增行</vxe-button>
    </div>

    <!--表格-->
    <div class="table_90 f-12">
      <h2 style="display: contents">
        关联成品型号
        <span style="font-size: 0.5em; font-weight: 500">（此处只关联上方半成品可生产的成品信息）</span>
      </h2>

      <el-button type="text" style="margin-left: 200px" size="small" @click="getProductList">获取成品信息</el-button>
      <vxe-table border :data="productList">
        <vxe-column field="product_sn" title="成品物料编码"></vxe-column>
        <vxe-column field="id" title="id" :visible="false"></vxe-column>
        <vxe-column field="product_name" title="成品物料名称"></vxe-column>
        <vxe-column field="product_sku" title="成品物料规格型号（sku）"></vxe-column>
      </vxe-table>
    </div>

    <div class="mold-header table_90 f-12">
      <el-row>
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-row>
            <el-col :span="6">
              <el-form-item label="模具类型" label-width="85px" required>
                <el-select v-model="formInline.type" filterable placeholder="请选择">
                  <el-option v-for="(item, key, index) of matrix_type" :key="key" :label="item"
                    :value="index"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="有无复制模" label-width="85px" required>
                <el-select v-model="formInline.is_copy_matrix" filterable placeholder="请选择">
                  <el-option v-for="(item, key, index) of is_copy_matrixs" :key="key" :label="item"
                    :value="index"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="模具费用" label-width="115px">
                <el-input v-model="formInline.cost_price" placeholder="模具费用"
                  onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)"
                  onafterpaste="this.value=this.value.match(/\d+\.?\d{0,2}/)" maxlength="7"
                  style="width: 220px"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="模具费用返还标准(万次)">
                <el-input v-model="formInline.return_standard" placeholder="模具费用返还标准(万次)"
                  onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)"
                  onafterpaste="this.value=this.value.match(/\d+\.?\d{0,2}/)" maxlength="7"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="申请开模时间">
                <el-date-picker v-model="formInline.matrix_start" type="date" placeholder="请选择申请开模时间"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="开模完成时间">
                <el-date-picker v-model="formInline.matrix_finish" type="date" placeholder="请选择开模完成时间"
                  style="110%"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="模具设计寿命(万次)">
                <el-input v-model="formInline.matrix_life" placeholder="模具设计寿命(万次)"
                  onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)"
                  onafterpaste="this.value=this.value.match(/\d+\.?\d{0,2}/)" maxlength="7"
                  style="width: 220px"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="模具状态" label-width="140px">
                <el-select v-model="formInline.status" filterable placeholder="请选择" style="width: 92%">
                  <el-option v-for="(item, key, index) of matrix_status" :key="key" :label="item"
                    :value="index"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="开模申请组织" label-width="95px" required>
                <el-select v-model="formInline.org_id" @change="changeOrg" filterable placeholder="请选择">
                  <el-option v-for="(item, index) in uc_orgs" :label="item.org_name" :value="item.org_id"
                    :key="index + '111'"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="开模申请部门" label-width="95px" required>
                <el-cascader @change="changeDept" :options="depts" :props="{
                    expandTrigger: 'hover',
                    value: 'dept_code',
                    label: 'dept_name',
                    children: 'children',
                    checkStrictly: true
                  }"></el-cascader>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="开模申请人" label-width="115px" required>
                <!-- <el-input v-model="formInline.applicant" placeholder="开模申请人" style="width:110%;"></el-input> -->
                <el-select v-model="formInline.matrix_apply" filterable placeholder="请选择">
                  <el-option v-for="(item, index) in uc_staffs" :label="item.staff_name" :value="item.staff_name"
                    :key="index + '111'"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="模具供应商" label-width="140px">
                <!-- <el-input v-model="formInline.supplier" placeholder="模具供应商" style="width:110%;"></el-input> -->
                <el-select v-model="formInline.supplier" filterable placeholder="请选择">
                  <el-option v-for="(item, index) in uc_suppliers" :label="item.sup_name" :value="item.sup_name"
                    :key="index + '222'"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="物料生产供应商(模具所在地）" label-width="85px" aligh="right">
                <el-select v-model="formInline.produc_supplier" filterable placeholder="请选择">
                  <el-option v-for="(item, index) in uc_suppliers" :label="item.sup_name" :value="item.sup_name"
                    :key="index + '333'"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="模具管理协议" label-width="100px">
                <el-upload class="upload-demo" :action="api_upload_url" :on-change="handleChange"
                  :on-preview="getDownload" :on-success="handleAvatarSuccess" :on-exceed="cickCtips" name="file"
                  :file-list="fileList" :with-credentials="true" :limit="1" :before-upload="onBeforeUpload"
                  :multiple="false" accept=".jpg, .png, .pdf">
                  <el-button size="small" type="primary">
                    <i class="el-icon-plus"></i>上传协议
                  </el-button>
                  <template #tip>
                    <div class="el-upload__tip">上传文件支持：jpg/png/pdf 最大限制上传： 10M</div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" label-width="100px">
                <vxe-textarea v-model="formInline.remark" placeholder="显示字数统计" rows="4" maxlength="255" show-word-count
                  style="width: 1500px"></vxe-textarea>
              </el-form-item>
            </el-col>
            <div class="click-btn">
              <el-button type="primary" size="small" @click="onSubmit" class="btn-save">保存</el-button>
              <!-- <el-button plain size="small" @click="cancel" class="btn-cancel">取消</el-button> -->
            </div>
          </el-row>
        </el-form>
      </el-row>
    </div>
  </div>
</template>

<script>
import { Plus, ZoomIn, Download, Delete } from '@element-plus/icons'
import { ElMessage } from 'element-plus'
import { mapActions, mapState } from 'vuex'
import download from 'downloadjs' //下载依赖
export default {
  components: {
    Plus,
    ZoomIn,
    Download,
    Delete,
  },
  data () {
    return {
      depts: [], //申请部门
      fileList: [],
      // imageUrl: '',          // 图片路径
      tableData: [],
      tableColumn: [],
      productList: [], //成品
      pro_num: [],
      formInline: {
        matrix_title: '',
        matrix_data: [],
        product_data: [], //提交的成品信息
        produce_sku: '',
        type: '',
        is_copy_matrix: '',
        cost_price: '',
        return_standard: '',
        matrix_start: '',
        matrix_finish: '',
        matrix_life: '',
        surplus_life: '',
        supplier: '',
        status: '',
        agreement: '',
        remark: '',
        matrix_apply: '',
        dotype: 'add',
        id: 0,
        org_id: '',
        dept_code: '',
      },
      //验证规则
      rules: {
        matrix_title: [
          { required: true, message: '请填写模具名称', trigger: 'blur' },
        ],
        matrix_apply: [
          { required: true, message: '请选择开模申请人', trigger: 'blur' },
        ],
      },
      value1: '',
      value2: '',
      is_copy_matrixs: {},
      matrix_type: {},
      matrix_status: {},
      uc_staffs: [],
      uc_suppliers: [],
      uc_orgs: [],
      is_submit: true,
      matrix_id: '',
    }
  },
  created () {
    this.matrix_id = this.$route.query.matrix_id
    this.getSupplierData()
    this.findList()
    this.getMaterialList()
  },
  //清除缓存
  activated () {
    this.matrix_id = this.$route.query.matrix_id
    if (this.$route.query.type == 0) {
      ; (this.fileList = []),
        (this.tableColumn = []),
        (this.formInline = {
          matrix_title: '',
          matrix_data: [],
          produce_sku: '',
          type: '',
          is_copy_matrix: '',
          cost_price: '',
          return_standard: '',
          matrix_start: '',
          matrix_finish: '',
          matrix_life: '',
          surplus_life: '',
          supplier: '',
          status: '',
          agreement: '',
          remark: '',
          matrix_apply: '',
          dotype: 'add',
          id: 0,
        })
    }
  },
  //清除缓存
  beforeRouteUpdate (to, from, next) {
    this.matrix_id = to.query.matrix_id
    if (to.fullPath != from.fullPath) {
      this.getSupplierData()
      next()
    }
  },
  computed: {
    api_upload_url () {
      var apiVersion = process.env.VUE_APP_API_VERSION.replace(/\./g, '_')
      return (
        process.env.VUE_APP_API_BASEURL + apiVersion + '/upload/uploadImgDemo'
      )
    },
    ...mapState({
      // 取出页面标签
      tags: (state) => state.topNavTag.tags,
    }),
  },
  methods: {
    ...mapActions({
      // 关闭标签及页面
      handleCloseTag: 'topNavTag/removeNavTag',
    }),
    getHolesNum (nusds, keyid, typee) {
      if (!/^[1-9]\d*$/.test(nusds)) {
        ElMessage({
          type: 'error',
          message: '请输入正整数',
        })
        this.tableColumn.forEach((item, index) => {
          if (keyid == item.keyid) {
            if (typee == 1) {
              item.holes_num = 0
            }
            if (typee == 2) {
              item.capacity_num = 0
            }
          }
        })
      }
    },
    getMatrixInfo (matrix_id) {
      this.formInline = {
        matrix_title: '',
        matrix_data: [],
        produce_sku: '',
        type: '',
        is_copy_matrix: '',
        cost_price: '',
        return_standard: '',
        matrix_start: '',
        matrix_finish: '',
        matrix_life: '',
        surplus_life: '',
        supplier: '',
        status: '',
        agreement: '',
        remark: '',
        matrix_apply: '',
        dotype: 'add',
        id: 0,
        org_id: 0,
        dept_code: 0,
      }
      this.tableColumn = []
      this.$http
        .post('matrix/getMatrixInfo', { id: matrix_id })
        .then((ress) => {
          if (ress.status == 200) {
            if (ress.data != '') {
              this.formInline = ress.data
              this.formInline.dotype = 'edit'
              this.tableColumn = ress.data.matrix_data_arr
              this.productList = ress.data.product_data
              console.log(this.productList)
              this.fileList = []
              if (ress.data.agreement != '') {
                var agreement = {
                  name: ress.data.agreement,
                  url: ress.data.agreement,
                }
                this.fileList.push(agreement)
              }
            }
            //获取部门组织
            this.getSupplierData()
            this.getDepts()
          }
        })
    },
    getMaterialList () {
      this.$http.post('matrix/getMaterial').then((ret) => {
        if (ret.status == 200) {
          this.pro_num = ret.data.results
        }
      })
    },
    //输入匹配
    getMaterial (produce_sn, keyid) {
      this.$http
        .post('matrix/getMaterial', { fnumber: produce_sn })
        .then((ret) => {
          if (ret.status == 200) {
            if (ret.data.results == '' || ret.data.results == null) {
              ElMessage({
                type: 'error',
                message: '该生产物料编码不存在！',
              })
              return false
            }
            this.tableColumn.forEach((item, index) => {
              if (keyid == item.keyid) {
                if (ret.data.results.FNAME == '') {
                  item.produce_titile = ''
                  item.produce_sku = ''
                  item.produce_id = ''
                } else {
                  item.produce_titile = ret.data.results.FNAME
                  item.produce_sku = ret.data.results.FSPECIFICATION
                  item.produce_id = ret.data.results.FMATERIALID
                }
              }
            })
          } else {
            ElMessage({
              type: 'error',
              message: '请求错误',
            })
          }
        })
    },

    getSupplierData () {
      this.$http.post('matrix/getSupplier', {}).then((ret) => {
        this.is_copy_matrixs = ret.data.is_copy_matrixs
        this.matrix_type = ret.data.matrix_type
        this.matrix_status = ret.data.matrix_status
        // this.uc_staffs = ret.data.uc_staffs
        this.uc_suppliers = ret.data.uc_suppliers
        this.uc_orgs = ret.data.uc_orgs
        // this.depts = ret.data.uc_depts
        if (this.matrix_id != '' || this.matrix_id != undifend) {
          this.getMatrixInfo(this.matrix_id)
        }
      })
    },
    //获取部门
    getDepts () {
      this.$http
        .get('matrix/getDepts', { org_id: this.formInline.org_id })
        .then((ret) => {
          this.depts = ret.data.uc_depts
        })
    },
    //获取员工
    getStaff () {
      this.$http
        .get('matrix/getStaffs', { org_id: this.formInline.org_id })
        .then((ret) => {
          this.uc_staffs = ret.data.uc_staffs
        })
    },

    //开模申请组织修改后
    changeOrg () {
      this.formInline.dept_code = '' //重置开模申请部门
      this.formInline.matrix_apply = '' //重置开模申请人
      //重新获取信息
      this.getDepts()
      this.getStaff()
    },
    changeDept (val) {
      console.log(val)
      this.formInline.dept_code = val[val.length - 1]
    },

    //删除行
    async removeRow (row) {
      console.log('row --->', row)
      // this.tableColumn.
      const $table = this.$refs.xTable

      await $table.remove(row)
      this.tableColumn.forEach((item, index) => {
        if (item.keyid == row.keyid) {
          this.tableColumn.splice(index, 1)
        }
      })
    },
    // 增加行
    async insertEvent (row) {
      const $table = this.$refs.xTable
      const record = {
        id: '',
        produce_sn: '',
        produce_titile: '',
        produce_sku: '',
        holes_num: 0,
        capacity_num: 0,
      }
      const { row: newRow } = await $table.insertAt(record, row)
      await $table.setActiveCell(newRow, 'name')
      this.tableColumn.push(newRow)
    },
    //表格
    findList () {
      this.loading = true
      var that = this
      setTimeout(() => {
        var list = [
          {
            id: '',
            produce_sn: '',
            produce_titile: '',
            produce_sku: '',
            holes_num: 0,
            capacity_num: 0,
          },
        ]
        that.tableColumn = list

        this.loading = false
      }, 100)
    },
    authRes () {
      this.tableColumn.forEach((item, index) => {
        if (item.produce_sku == undefined) {
          ElMessage({ type: 'error', message: '可生产物料编码不存在' })
          return false
        }
      })

      setTimeout(() => {
        this.is_submit = true
      }, 500)
    },
    //保存提交
    onSubmit () {
      this.authRes()
      if (this.is_submit == true) {
        //获取成品信息 再提交
        this.$http
          .post('matrix/getProduct', { list: this.tableColumn })
          .then((ret) => {
            if (ret.status == 200) {
              this.productList = ret.data.results
            }
            //提交
            this.formInline.matrix_data = JSON.stringify(this.tableColumn)
            this.formInline.product_data = JSON.stringify(this.productList)
            this.$http
              .post('matrix/saveMatrix', this.formInline)
              .then((ret) => {
                if (ret.status == 200) {
                  ElMessage({
                    type: 'success',
                    message: ret.message,
                  })
                  this.$router.push({
                    path: '/mold/index',
                  })
                  const currentPageName = this.$route.name
                  const tags = this.tags
                  const idx = tags.findIndex(
                    (it) => it.name === currentPageName
                  )
                  if (idx >= 0) {
                    this.handleCloseTag(idx)
                  }
                } else {
                  ElMessage({
                    type: 'error',
                    message: ret.message,
                  })
                }
              })
          })
      }
    },
    //关闭子页面
    cancel () {
      // let routeData = this.$router.push({
      //   path: '/mold/index',
      // });
      // window.opener = null;
      // // //新页面中,才能使用如下关闭
      // window.close()

      this.handleCloseTag()
    },
    getProductList () {
      //半成品物料为空判断
      if (this.tableColumn.length <= 0) {
        ElMessage({
          type: 'error',
          message: '请填写半成品物料',
        })
        return false
      }
      this.$http
        .post('matrix/getProduct', { list: this.tableColumn })
        .then((ret) => {
          if (ret.status == 200) {
            this.productList = ret.data.results
          } else {
            ElMessage({
              type: 'error',
              message: ret.message,
            })
          }
        })
    },

    //上传文件校验
    onBeforeUpload (file) {
      const isIMAGE =
        file.type === 'image/jpg' ||
        file.type === 'image/jpeg' ||
        file.type === 'application/pdf' ||
        file.type === 'image/png'
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isIMAGE) {
        ElMessage({
          type: 'error',
          message: '上传文件格式错误!',
        })
        this.fileList = []
      }
      if (!isLt10M) {
        ElMessage({
          type: 'error',
          message: '超出文件上传大小!',
        })
        this.fileList = []
      }
      return isIMAGE && isLt10M
    },

    //远程输入框搜索
    querySearchAsync (queryString, cb) {
      var restaurants = this.restaurants
      var results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants

      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        cb(results)
      }, 3000 * Math.random())
    },
    createStateFilter (queryString) {
      return (state) => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        )
      }
    },
    handleSelect (item) {
      console.log(item)
    },
    //下载
    getDownload () {
      download(this.formInline.agreement)
    },

    //正负数，含小数
    isFloor () {
      var obj = event.target
      var t = obj.value.charAt(0)
      obj.value = obj.value
        .replace('.', '$#$') //把第一个字符'.'替换成'$#$'
        .replace(/\./g, '') //把其余的字符'.'替换为空
        .replace('$#$', '.') //把字符'$#$'替换回原来的'.'
        .replace(/[^\d.]/g, '') //只能输入数字和'.'
        .replace(/^\./g, '') //不能以'.'开头
        .replace(/([0-9]+\.[0-9]{2})[0-9]*/, '$1') //只保留2位小数
      if (t == '-') {
        obj.value = '-' + obj.value
      }
    },
    // 管理上传
    handleAvatarSuccess (res, file) {
      this.formInline.agreement = res.data.imgpath
    },
    handleChange (file, fileList) {
      this.fileList = fileList.slice(-3)
    },
    cickCtips (files, fileList) {
      ElMessage({
        type: 'error',
        message: '文件已上传，如要替换请先删除！',
      })
    },
  },
}
</script>
<style scoped>
::v-deep(
    .vxe-table--render-default .vxe-body--column:not(.col--ellipsis),
    .vxe-table--render-default .vxe-footer--column:not(.col--ellipsis),
    .vxe-table--render-default .vxe-header--column:not(.col--ellipsis)
  ) {
  padding: 5px 0;
  font-size: 12px;
}
::v-deep(.el-form-item__label) {
  line-height: 22px;
  padding: 8px 12px 12px 0;
  font-size: 12px;
}
::v-deep(.vxe-table--main-wrapper) {
  font-size: 12px;
}
.mold-header {
  margin: 20px;
}
.m-t-20 {
  margin: 20px 0;
}
::v-deep(.el-form-item) {
  margin-bottom: 20px;
}
.u-t-r {
  text-align: right;
}

.click-btn {
  width: 100%;
  margin: auto;
  text-align: center;
}
.btn-save {
  width: 150px;
  line-height: 28px;
  margin-right: 20px;
  margin-right: 20px;
}
.btn-cancel {
  width: 150px;
  line-height: 28px;
}
</style>
