<!--
 * @Author: liuzhenlin 461480418@qq.ocm
 * @Date: 2023-01-09 15:49:34
 * @LastEditors: liuzhenlin
 * @LastEditTime: 2023-01-11 19:11:20
 * @Description: file content
 * @FilePath: \订单全流程管理系统\src\views\contract\components\Edit.vue
-->
<template>
  <el-dialog class="edit-container" :title="title" top="5vh" :visible.sync="editVisible" @close="handleClose">
    <div class="setp-wrap">
      <el-steps :active="stepActive" :align-center="true" finish-status="success">
        <el-step title="基础信息" />
        <el-step title="产品列表" />
      </el-steps>
    </div>
    <el-form v-show="stepActive == 0" ref="editForm" :model="editForm" :rules="editRules">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="合同编号" prop="contractCode">
            <el-input v-model="editForm.contractCode" disabled placeholder="根据编号规则自动生产" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关联项目" prop="nboName">
            <el-input
              v-model="editForm.nboName"
              :disabled="businessData.length > 0"
              placeholder="请选择关联项目"
              readonly
              suffix-icon="el-icon-search"
              @focus="openProject" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="合同名称" prop="contractName">
            <el-input v-model="editForm.contractName" placeholder="请输入合同名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="nboId">
            <el-input v-model="editForm.custName" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="合同开始时间" prop="contractStartTime">
            <el-date-picker
              v-model="editForm.contractStartTime"
              :picker-options="pickerOptionsStart"
              placeholder="选择开始日期"
              style="width: 100%"
              type="date"
              value-format="yyyy-MM-dd" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同结束时间" prop="contractEndTime">
            <el-date-picker
              v-model="editForm.contractEndTime"
              :picker-options="pickerOptionsEnd"
              placeholder="选择结束日期"
              style="width: 100%"
              type="date"
              value-format="yyyy-MM-dd" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="销售工程师" prop="inchargeName">
            <el-input
              v-model="editForm.inchargeName"
              :disabled="editForm.id > 0"
              placeholder="请选择销售工程师"
              readonly
              suffix-icon="el-icon-search"
              @focus="openUser(false, 'inchargeId', 'inchargeName')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公司签约人" prop="signatoryName">
            <el-input
              ref="signatoryName"
              v-model="editForm.signatoryName"
              placeholder="请选择公司签约人"
              readonly
              suffix-icon="el-icon-search"
              @focus="openUser(false, 'signatoryId', 'signatoryName')" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="经销商" prop="distributorName">
            <el-input
              v-model="editForm.distributorName"
              placeholder="请选择经销商"
              readonly
              suffix-icon="el-icon-search"
              @focus="openDistributor" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同类型" prop="contractType">
            <el-select v-model="editForm.contractType" placeholder="合同类型" style="width: 100%">
              <el-option v-for="item in contractOptions" :key="item.value" :label="item.value" :value="item.key" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="签订单位类型" prop="signatoryType">
            <el-select v-model="editForm.signatoryType" placeholder="签订单位类型" style="width: 100%">
              <el-option v-for="item in signatoryOptions" :key="item.value" :label="item.value" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="客户签约人" prop="custSignatoryName">
            <el-input
              v-model="editForm.custSignatoryName"
              :disabled="!businessUserQueryParams.busId"
              placeholder="请选择客户签约人"
              readonly
              suffix-icon="el-icon-search"
              @focus="openContact" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="editForm.remark" placeholder="请输入备注" :rows="5" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 产品分类 -->
    <el-row v-show="stepActive == 1">
      <el-row class="mb10" :gutter="20">
        <el-col :span="12">
          <p>产品：</p>
        </el-col>
        <el-col class="proj-col" :span="12">
          <el-button type="primary" @click="$refs.product.open()">选择产品</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <product-table
            ref="productTable"
            :product-data="productData"
            @changeProductData="changeProductData"
            @delProductData="delProductData" />
        </el-col>
      </el-row>
    </el-row>

    <span slot="footer">
      <el-button v-show="stepActive == 0" type="primary" @click="setStep(1)">下一步</el-button>
      <el-button v-show="stepActive == 1" type="primary" @click="setStep(0)">上一步</el-button>
      <el-button v-show="!editForm.id && stepActive == 1" type="primary" @click="contractSave">保存</el-button>
      <el-button v-show="editForm.id && stepActive == 1" type="primary" @click="contractEdit">保存</el-button>
      <el-button @click="editVisible = false">取消</el-button>
    </span>
    <!-- 选择项目 -->
    <select-business ref="project" :multiple="false" @save="getBusinessInfo" />
    <!-- 选择经销商 -->
    <select-distributor ref="distributor" :multiple="false" @save="getDistributor" />
    <!-- 选择用户 -->
    <select-user ref="user" :label="label" :multiple="multiple" :property="property" @save="getUser" />
    <!-- 选择产品 -->
    <select-product ref="product" :multiple="true" @save="getProduct" />
    <!-- 选择联系人 -->
    <select-business-contact
      ref="contact"
      :multiple="false"
      :query-params="businessUserQueryParams"
      @save="getContact" />
  </el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import to from 'await-to-js'
  import contractApi from '@/api/contract'
  import businessApi from '@/api/proj/business'
  import ProductTable from './ProductTable'
  import SelectBusiness from '@/components/select/SelectBusiness'
  import SelectDistributor from '@/components/select/SelectDistributor'
  import SelectUser from '@/components/select/SelectUser'
  import SelectProduct from '@/components/select/SelectProduct'
  import SelectBusinessContact from '@/components/select/SelectBusinessContact'
  export default {
    components: {
      ProductTable,
      SelectBusiness,
      SelectDistributor,
      SelectUser,
      SelectProduct,
      SelectBusinessContact,
    },
    props: {
      businessData: {
        type: Array,
        default: () => [],
      },
    },
    data() {
      return {
        stepActive: 0, //步骤
        title: '新增客户信息',
        editVisible: false,
        editForm: {
          contractCode: '', //合同编号
          contractName: '', //合同名称
          contractType: '', //合同类型
          nboId: null, //项目id
          nboName: '', //项目名称
          custName: '', // 客户名称
          inchargeId: null, //销售工程师
          inchargeName: '', //销售工程师姓名
          signatoryType: '',
          contractStartTime: '', //合同开始时间
          contractEndTime: '', //合同结束时间
          signatoryName: '', //公司签约人
          signatoryId: null, //公司签约人id
          distributorId: null, //经销商id
          distributorName: '', //经销商name
          custSignatoryId: null, //客户签约人id
          custSignatoryName: '', //客户签约人name
          remark: '', //备注
        },
        editRules: {
          contractName: [{ required: true, trigger: 'blur', message: '请输入合同名称' }],
          contractType: [{ required: true, trigger: 'change', message: '请选择合同类型' }],
          signatoryType: [{ required: true, trigger: 'change', message: '请选择签订单位类型' }],
          nboName: [{ required: true, trigger: 'change', message: '请选择关联项目' }],
          contractStartTime: [
            { required: true, trigger: 'change', validator: this.pickerOptionsStart, message: '请选择开始时间' },
          ],
          contractEndTime: [{ trigger: 'change', validator: this.pickerOptionsEnd, message: '请选择结束时间' }],
          inchargeId: [{ required: true, trigger: 'change', message: '请选择销售工程师' }],
          signatoryName: [{ required: true, trigger: 'change', message: '请选择公司签约人' }],
          distributorName: [{ trigger: 'change', message: '请选择经销商' }],
        },
        pickerOptionsStart: {
          disabledDate: (time) => {
            let endDateVal = this.editForm.contractEndTime
            if (endDateVal) {
              return time.getTime() > new Date(endDateVal).getTime()
            }
          },
        },
        pickerOptionsEnd: {
          disabledDate: (time) => {
            let beginDateVal = this.editForm.contractStartTime
            if (beginDateVal) {
              return time.getTime() < new Date(beginDateVal).getTime() - 1 * 24 * 60 * 60 * 1000
            }
          },
        },
        contractOptions: [], //合同类型
        signatoryOptions: [
          {
            key: '10',
            value: '终端用户',
          },
          {
            key: '20',
            value: '经销商',
          },
          {
            key: '30',
            value: '代理商',
          },
        ], //合同类型
        productData: [],
        multiple: false,
        property: '',
        label: '',
        businessUserQueryParams: {}, //查询客户签约人参数
      }
    },
    computed: {
      ...mapGetters({
        userId: 'user/id',
        username: 'user/username',
      }),
    },
    mounted() {
      this.getOptions()
    },
    methods: {
      getOptions() {
        Promise.all([this.getDicts('contract_type')])
          .then(([contract]) => {
            this.contractOptions = contract.data.values || []
          })
          .catch((err) => console.log(err))
      },
      async init(id) {
        if (this.businessData[0]) this.getBusinessInfo(this.businessData)
        if (!id) {
          this.title = '新增合同信息'
          // 设置销售工程师默认为当前用户
          this.editForm.inchargeId = this.userId
          this.editForm.inchargeName = this.nickName
          this.editForm.signatoryId = this.userId
          this.editForm.signatoryName = this.nickName
        } else {
          this.title = '编辑合同'
          const [err, res] = await to(contractApi.getDetails({ id }))
          if (err) return
          if (res.data) {
            // eslint-disable-next-line no-unused-vars
            let { product, ...data } = res.data
            this.editForm = data
            this.businessUserQueryParams = { busId: data.nboId, custId: data.custId }
            this.productData =
              product.length > 0
                ? product.map((item) => ({
                    prodCode: item.prodCode,
                    id: item.prodId,
                    prodName: item.prodName,
                    prodClass: item.prodClass,
                    guidPrice: item.sugSalesPrice,
                    price: item.tranPrice,
                    count: item.prodNum,
                  }))
                : []
          }
        }
        this.editVisible = true
      },
      // 修改步骤
      async setStep(step) {
        if (step == 1) {
          const [valid] = await to(this.$refs.editForm.validate())
          if (valid == false) return
        }
        this.stepActive = step
      },
      // 打开选择项目
      openProject() {
        this.$refs.project.open()
      },
      // 关闭选择项目获取项目信息
      getBusinessInfo(data) {
        let business = data[0] || null
        if (!business) return

        this.editForm.contractName = business.nboName
        this.editForm.custName = business.custName
        this.editForm.nboId = business.id
        this.editForm.nboName = business.nboName
        this.editForm.custSignatoryId = business.contactId
        this.editForm.custSignatoryName = business.contactName
        this.businessUserQueryParams = { busId: business.id, custId: business.custId }
        // 获取产品信息
        this.getProjectInfo(business.id)
      },
      // 打开选择经销商
      openDistributor() {
        this.$refs.distributor.open()
      },
      // 关闭经销商获取经销商信息
      getDistributor(data) {
        let distributor = data[0] || null
        if (!distributor) return
        this.editForm.distributorName = distributor.distName
        this.editForm.distributorId = distributor.id
      },
      // 打开选择公司签约人
      openUser(multiple, property, label) {
        this.multiple = multiple
        this.property = property
        this.label = label
        if (this.editForm[property].length) {
          this.$refs.user.ids = this.editForm[property]
        } else if (this.editForm[property]) {
          this.$refs.user.ids = [this.editForm[property]]
        } else {
          this.$refs.user.ids = []
        }
        this.$refs.user.open()
      },
      // 获取签约人信息
      getUser(userList, property, label) {
        this.editForm[label] = userList.map((item) => item.nickName).join()
        if (this.multiple) {
          this.editForm[property] = userList.map((item) => item.id)
        } else {
          this.editForm[property] = userList[0] ? userList[0].id : ''
        }
        this.$forceUpdate()
      },
      // 打开选择公司签约人
      openContact() {
        this.$refs.contact.open()
      },
      // 获取签约人信息
      getContact(data) {
        let user = data[0] || null
        if (!user) return
        this.editForm['custSignatoryName'] = user.userName
        this.editForm['custSignatoryId'] = user.id
      },
      // 获取产品信息
      getProduct(data) {
        // 重构产品数据结构
        if (data.length > 0) this.setProductData(data)
      },
      // 根据项目id获取产品信息
      async getProjectInfo(id) {
        let params = { id }
        const [err, res] = await to(businessApi.getProductByBusinessId(params))
        if (err) return
        if (res.data && res.data.length > 0) this.setProductData(res.data)
      },
      setProductData(data) {
        let projData = data.map((item) => ({
          id: item.prodId ? item.prodId : item.id,
          prodName: item.prodName,
          prodCode: item.prodCode,
          prodClass: item.prodClass,
          guidPrice: item.guidPrice,
          price: item.prodPrice ? item.prodPrice : item.guidPrice,
          count: 1,
        }))
        this.productData.push(...projData)
        this.productData = this.removeDuplicateObj(this.productData)
      },
      // 数组对象去重
      removeDuplicateObj(arr) {
        let obj = {}
        arr = arr.reduce((newArr, next) => {
          obj[next.id] ? '' : (obj[next.id] = true && newArr.push(next))
          return newArr
        }, [])
        return arr
      },
      // 修改产品列表数据
      changeProductData(data) {
        this.productData = this.productData.map((item) => {
          return item.id === data.id ? data : item
        })
      },
      delProductData(data) {
        this.productData = this.productData.filter((item) => item.id != data.id)
      },
      // 保存合同
      async contractSave() {
        let product = this.productData.map((item) => ({
          prodId: item.id,
          prodNum: parseInt(item.count),
          maintTerm: 1,
          sugSalesPrice: item.guidPrice,
          tranPrice: item.price,
          remark: '',
        }))
        let params = Object.assign({ ...this.editForm }, { product })
        if (product.length == 0) return this.$message.warning('请选择产品信息')
        const [err, res] = await to(contractApi.addContract(params))
        if (err) return
        if (res.code == 200) this.$message.success(res.msg)
        else return
        this.editVisible = false
        this.$emit('contractSave')
      },
      // 编辑合同
      async contractEdit() {
        let product = this.productData.map((item) => ({
          prodId: item.id,
          prodNum: parseInt(item.count),
          maintTerm: 1,
          sugSalesPrice: item.guidPrice,
          tranPrice: item.price,
          remark: '',
        }))
        let params = Object.assign({ ...this.editForm }, { product })
        if (product.length == 0) return this.$message.warning('请选择产品信息')
        const [err, res] = await to(contractApi.updateContract(params))
        if (err) return
        if (res.code == 200) this.$message.success(res.msg)
        else return
        this.editVisible = false
        this.$emit('contractSave')
      },
      handleClose() {
        this.editForm = {
          contractCode: '', //合同编号
          contractName: '', //合同名称
          contractType: '', //合同类型
          nboId: null, //项目id
          nboName: '', //项目名称
          custName: '', // 客户名称
          inchargeId: null, //销售工程师
          inchargeName: '', //销售工程师名称
          signatoryType: '',
          contractStartTime: '', //合同开始时间
          contractEndTime: '', //合同结束时间
          signatoryName: '', //公司签约人
          signatoryId: null, //公司签约人id
          distributorId: null, //经销商id
          distributorName: '', //经销商name
          remark: '', //备注
        }
        this.productData = []
        this.stepActive = 0
        this.businessUserQueryParams = {}
        this.$refs.editForm.resetFields()
      },
    },
  }
</script>

<style lang="scss" scoped>
  $base: '.edit-container';
  #{$base} {
    .mb10 {
      margin-bottom: 10px;
    }
    .proj-col {
      text-align: right;
    }
    // 进度条样式
    // ::v-deep .el-steps {
    //   .el-step__line {
    //     top: 17px;
    //   }
    //   .el-step__icon {
    //     width: 35px;
    //     height: 35px;
    //     font-size: 18px;
    //   }
    //   .is-process {
    //     .el-step__icon {
    //       background: #2e51ff;
    //       color: #fff;
    //       border-color: #2e51ff;
    //     }
    //   }
    // }
  }
</style>
