<template>
  <div style="display: inline-block; margin: 0 10px">
    <!--未在审批中 且级别为 B、C、储备 可升级-->
    <el-button
      v-permissions="['proj:business:upgrade']"
      :disabled="!['20', '30', '50'].includes(businessInfo.nboType) || businessInfo.approStatus === '20'"
      type="primary"
      @click="handleClick('up')">
      升级
    </el-button>
    <!--未在审批中 且级别为 A、B 可降级-->
    <el-button
      v-permissions="['proj:business:downgrade']"
      :disabled="!['10', '20'].includes(businessInfo.nboType) || businessInfo.approStatus === '20'"
      type="danger"
      @click="handleClick('down')">
      降级
    </el-button>

    <el-dialog append-to-body :title="title" :visible.sync="dialogFormVisible" width="60%" @close="close">
      <el-form
        v-if="type === 'up'"
        ref="form"
        label-position="top"
        :model="form"
        :rules="rules"
        style="margin-top: -20px">
        <el-form-item label="项目类别" prop="nboType">
          <el-select v-model="form.nboType" placeholder="请选择项目类别" style="width: 100%">
            <el-option
              :disabled="
                (type === 'up' && businessInfo.nboType === '10') ||
                (type === 'down' && ['10', '20'].includes(businessInfo.nboType))
              "
              label="A"
              value="10" />
            <el-option :disabled="businessInfo.nboType === '20'" label="B" value="20" />
            <el-option
              :disabled="type === 'up' && ['10', '20', '30'].includes(businessInfo.nboType)"
              label="C"
              value="30" />
            <!--            <el-option v-if="type === 'down'" label="储备" value="50" />-->
          </el-select>
        </el-form-item>
        <!--   C-B     必填项：项目类别、项目预算、渠道销售人员、渠道销售电话、微信、预计出货金额（不填）、添加产品、上传报价单  -->
        <el-row v-if="form.nboType !== '30'" :gutter="20">
          <el-col :span="8">
            <el-form-item label="项目预算" prop="nboBudget">
              <amount-input v-model.trim="form.nboBudget" placeholder="请输入金额" />
            </el-form-item>
          </el-col>
          <div v-if="businessInfo.salesModel !== '10'">
            <el-col :span="8">
              <el-form-item label="渠道销售人员" prop="dealerSalesName">
                <el-input
                  v-model="form.dealerSalesName"
                  readonly
                  suffix-icon="el-icon-search"
                  @focus="handleSelectDistributorContact" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="渠道销售电话/微信" prop="dealerSalesContact">
                <el-input v-model="form.dealerSalesContact" />
              </el-form-item>
            </el-col>
          </div>
          <el-col :span="8">
            <el-form-item
              label="报价单"
              prop="quotationFile"
              :required="form.nboType === '10' || form.nboType === '20'">
              <el-upload
                :action="uploadFileUrl"
                :file-list="quotationFileList"
                :limit="1"
                :on-success="setQuotationFile">
                <el-button size="mini" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div style="float: right; margin-bottom: 10px">
              <span style="margin-right: 10px; color: red">预计出货金额：{{ formatPrice(form.estTransPrice) }}</span>
              <el-button size="mini" type="primary" @click="handleSelectProduct">添加产品</el-button>
            </div>

            <product-table
              ref="productTable"
              :product-data="productData"
              @changeProductData="changeProductData"
              @delProductData="delProductData" />
          </el-col>
        </el-row>
        <!--    B-A    必填项：采购方式、资金来源、计划采购时间、客户决策人、客户决策部分、客户联系人姓名、客户联系人电话/微信、是否采纳我司技术参数（是/否）、竞争公司、客户倾向厂家  -->
        <el-row v-if="form.nboType === '10'" :gutter="20">
          <el-col :span="8">
            <el-form-item label="采购方式" prop="purchasingWay" :required="type === 'up' && form.nboType === '10'">
              <el-select v-model="form.purchasingWay" placeholder="请选择" style="width: 100%">
                <el-option v-for="item in purchasingWayOptions" :key="item.key" :label="item.value" :value="item.key" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="资金来源" prop="capitalSource">
              <el-input v-model="form.capitalSource" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="计划采购时间"
              prop="planPurchaseTime"
              :required="type === 'up' && form.nboType === '10'">
              <el-date-picker
                v-model="form.planPurchaseTime"
                placeholder="选择日期"
                style="width: 100%"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户决策人" prop="makerName">
              <el-input v-model="form.makerName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户决策部门" prop="makerDept">
              <el-input v-model="form.makerDept" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户联系人" prop="contactName">
              <el-input
                v-model="form.contactName"
                readonly
                suffix-icon="el-icon-search"
                @focus="handleSelectCustomerContact" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户联系人电话/微信" prop="contactTelephone">
              <el-input v-model="form.contactTelephone" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="竞争公司" prop="competitor">
              <el-input v-model="form.competitor" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户倾向厂家" prop="customerIntentionFactory">
              <el-input v-model="form.customerIntentionFactory" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="是否采纳大数技术参数"
              prop="isAdoptDashoo"
              :required="type === 'up' && form.nboType === '10'">
              <el-radio-group v-model="form.isAdoptDashoo" style="width: 100%">
                <el-radio label="10">是</el-radio>
                <el-radio label="20">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.isAdoptDashoo === '10'" :span="8">
            <el-form-item label="参数文件" prop="dashooParamFile" :required="form.isAdoptDashoo === '10'">
              <el-upload
                :action="uploadFileUrl"
                :file-list="dashooParamFileList"
                :limit="1"
                :on-success="setDashooParamFile">
                <el-button size="mini" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.nboType === '30'">
          <el-form-item label="转化原因" prop="projConversionReason">
            <el-input
              v-model="form.projConversionReason"
              maxlength="300"
              placeholder="请输入转化原因"
              rows="3"
              show-word-limit
              type="textarea" />
          </el-form-item>
        </el-row>
        <el-row v-else>
          <el-col :span="24">
            <el-form-item label="升级原因" prop="remark">
              <el-input
                v-model="form.remark"
                maxlength="300"
                placeholder="请输入备注原因"
                rows="3"
                show-word-limit
                type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form
        v-if="type === 'down'"
        ref="form"
        label-position="top"
        :model="form"
        :rules="rules"
        style="margin-top: -20px">
        <el-form-item label="项目类别" prop="nboType">
          <el-select v-model="form.nboType" placeholder="请选择项目类别" style="width: 100%">
            <el-option
              :disabled="
                (type === 'up' && businessInfo.nboType === '10') ||
                (type === 'down' && ['10', '20'].includes(businessInfo.nboType))
              "
              label="A"
              value="10" />
            <el-option :disabled="businessInfo.nboType === '20'" label="B" value="20" />
            <el-option
              :disabled="type === 'up' && ['10', '20', '30'].includes(businessInfo.nboType)"
              label="C"
              value="30" />
            <!--            <el-option v-if="type === 'down'" label="储备" value="50" />-->
          </el-select>
        </el-form-item>
        <el-form-item label="降级原因" prop="remark" required>
          <el-input
            v-model="form.remark"
            maxlength="300"
            placeholder="请输入备注原因"
            rows="3"
            show-word-limit
            type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="close">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="save">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 选择客户联系人弹窗 -->
    <select-customer-contact
      ref="selectCustomerContact"
      :default-customer="customerInfo"
      :query-params="queryCustomerContact"
      @save="selectCustomerContact" />
    <!-- 选择渠道销售人员弹窗 -->
    <select-distributor-contact
      ref="selectDistributorContact"
      :default-dist="distInfo"
      :query-params="queryDistContact"
      @save="selectDistributorContact" />
    <!-- 选择产品弹窗 -->
    <select-product ref="selectProduct" multiple @save="selectProduct" />
  </div>
</template>

<script>
  import to from 'await-to-js'
  import businessApi from '@/api/proj/business'
  import AmountInput from '@/components/currency/index.vue'
  import SelectCustomerContact from '@/components/select/SelectCustomerContact'
  import SelectDistributorContact from '@/components/select/SelectDistributorContact'
  import ProductTable from '@/views/proj/business/components/ProductTable.vue'
  import SelectProduct from '@/components/select/SelectProduct'

  export default {
    name: 'BusinessGradation',
    components: {
      SelectProduct,
      ProductTable,
      AmountInput,
      SelectCustomerContact,
      SelectDistributorContact,
    },
    props: {
      // 项目Id
      busId: {
        type: Number,
        required: true,
      },
      // 项目类别
      businessInfo: {
        type: Object,
        required: true,
      },
    },
    data() {
      const validateDowngrade = (rule, value, callback) => {
        if (!value && this.type === 'down') callback(new Error('不能为空'))
        else callback()
      }
      const validateNboBudget = (rule, value, callback) => {
        if (parseInt(value) <= 0) callback(new Error())
        else callback()
      }
      const validateAdoptDashoo = (rule, value, callback) => {
        if (this.form.isAdoptDashoo === '10' && !value) callback(new Error())
        else callback()
      }
      return {
        title: '项目',
        type: '',
        loading: false,
        form: {
          id: undefined,
          nboType: undefined,
          // C => B
          nboBudget: undefined,
          dealerSalesId: undefined,
          dealerSalesName: undefined,
          dealerSalesContact: undefined,
          estTransPrice: undefined,
          quotationFile: undefined,
          products: [],
          // B => A
          purchasingWay: undefined,
          capitalSource: undefined,
          planPurchaseTime: undefined,
          contactId: undefined,
          contactName: undefined,
          contactTelephone: undefined,
          contactWechat: undefined,
          makerId: undefined,
          makerName: undefined,
          makerDept: undefined,
          makerPost: undefined,
          makerTelephone: undefined,
          customerIntentionFactory: undefined,
          competitor: undefined,
          isAdoptDashoo: undefined,
          dashooParamFile: undefined,
          projConversionReason: undefined,
          remark: undefined,
        },
        rules: {
          nboType: [{ required: true, trigger: ['blur', 'change'], message: '请选择项目类别' }],
          // C => B
          nboBudget: [
            { required: true, trigger: ['blur', 'change'], message: '请输入项目预算' },
            { validator: validateNboBudget, trigger: ['blur', 'change'], message: '项目预算应大于0' },
          ],
          dealerSalesId: [{ required: true, trigger: ['blur', 'change'], message: '请选择渠道销售' }],
          dealerSalesName: [{ required: true, trigger: ['blur', 'change'], message: '请选择项渠道销售人员' }],
          dealerSalesContact: [{ required: true, trigger: ['blur', 'change'], message: '请输入渠道销售电话/微信' }],
          estTransPrice: [{ required: true, trigger: ['blur', 'change'], message: '请选择预计出货金额' }],
          quotationFile: [{ required: true, trigger: ['blur', 'change'], message: '请选择报价单' }],
          products: [{ required: true, trigger: ['blur', 'change'], message: '请选择产品' }],
          // B => A
          purchasingWay: [{ required: true, trigger: ['blur', 'change'], message: '请选择采购方式' }],
          capitalSource: [{ required: true, trigger: ['blur', 'change'], message: '请输入资金来源' }],
          planPurchaseTime: [{ required: true, trigger: ['blur', 'change'], message: '请选择计划采购时间' }],
          contactId: [{ required: true, trigger: ['blur', 'change'], message: '请选择客户联系人' }],
          contactName: [{ required: true, trigger: ['blur', 'change'], message: '请选择客户联系人姓名' }],
          contactTelephone: [{ required: true, trigger: ['blur', 'change'], message: '请输入客户联系人电话/微信' }],
          makerId: [{ required: true, trigger: ['blur', 'change'], message: '请选择客户决策人' }],
          makerName: [{ required: true, trigger: ['blur', 'change'], message: '请选择客户决策人姓名' }],
          makerDept: [{ required: true, trigger: ['blur', 'change'], message: '请选择客户决策部门' }],
          customerIntentionFactory: [{ required: true, trigger: ['blur', 'change'], message: '请输入客户倾向厂家' }],
          competitor: [{ required: true, trigger: ['blur', 'change'], message: '请输入竞争公司' }],
          isAdoptDashoo: [{ required: true, trigger: ['blur', 'change'], message: '请选择是或否' }],
          dashooParamFile: [{ validator: validateAdoptDashoo, trigger: ['blur', 'change'], message: '请选择上传文件' }],
          projConversionReason: [{ required: true, trigger: ['blur', 'change'], message: '请输入转化原因' }],
          remark: [{ validator: validateDowngrade, trigger: ['blur', 'change'], message: '请输入原因' }],
        },
        dialogFormVisible: false,
        purchasingWayOptions: [],
        // 大数参数文件
        dashooParamFileList: [],
        quotationFileList: [],
        uploadFileUrl: process.env.VUE_APP_UPLOAD_FILE_WEED,
        fileSettings: {
          // 文件配置信息
          fileSize: 52428800,
          fileTypes: '.doc,.docx,.zip,.xls,.xlsx,.rar,.jpg,.jpeg,.gif,.png,.jfif,.txt',
          pictureSize: 52428800,
          pictureTypes: '.jpg,.jpeg,.gif,.png,.jfif,.txt',
          types: '.doc,.docx,.zip,.xls,.xlsx,.rar,.jpg,.jpeg,.gif,.png,.jfif,.mp4,.txt',
          videoSize: 104857600,
          videoType: '.mp4',
        },
        queryCustomerContact: {},
        customerInfo: {},
        queryDistContact: {},
        distInfo: {},
        productData: [],
      }
    },
    mounted() {
      this.getDicts('proj_purchasing_way').then((response) => {
        this.purchasingWayOptions = response.data.values || []
      })
    },
    methods: {
      selectProduct(data) {
        let projData = data.map((item) => ({
          prodId: item.id,
          prodCode: item.prodCode,
          prodName: item.prodName,
          prodClass: item.prodClass,
          guidPrice: item.guidPrice,
          prodPrice: item.marketPrice,
          prodNum: 1,
        }))
        this.productData.push(...projData)
        this.productData = this.removeDuplicateObj(this.productData)
        this.getEstTransPrice()
      },
      // 数组对象去重
      removeDuplicateObj(arr) {
        let newArrId = []
        let newArrObj = []
        arr.forEach((item) => {
          if (!newArrId.includes(item.prodId)) {
            newArrId.push(item.prodId)
            newArrObj.push(item)
          }
        })
        return newArrObj
      },
      handleSelectProduct() {
        this.$refs.selectProduct.open()
      },
      // 修改产品列表数据
      changeProductData(data) {
        this.productData = this.productData.map((item) => {
          return item.prodId === data.prodId ? data : item
        })
        this.getEstTransPrice()
      },
      delProductData(data) {
        this.productData = this.productData.filter((item) => item.prodId !== data.prodId)
        this.getEstTransPrice()
      },
      getEstTransPrice() {
        this.form.estTransPrice = 0
        for (let item of this.productData) {
          console.log(item, '--------------------')
          this.form.estTransPrice += parseFloat(item.prodNum) * parseFloat(item.prodPrice)
        }
      },
      async getProductData(busId) {
        const { data } = await businessApi.getProductByBusinessId({ id: busId })
        if (data) {
          this.productData = data
        }
      },
      // 上传文件
      setDashooParamFile(res) {
        // 如果上传成功
        if (res.Code === 200) {
          this.form.dashooParamFile = res.Data
        } else {
          this.$message.error('上传文件失败')
        }
      },
      setQuotationFile(res) {
        // 如果上传成功
        if (res.Code === 200) {
          this.form.quotationFile = res.Data
        } else {
          this.$message.error('上传文件失败')
        }
      },
      handleSelectCustomerContact() {
        if (!this.queryCustomerContact.custId) {
          this.$message.warning('请先选择客户')
          return
        }
        this.$refs.selectCustomerContact.open()
      },
      selectCustomerContact(val) {
        if (val && val.length > 0) {
          this.form.contactId = val[0].id
          this.form.contactName = val.map((item) => item.cuctName).join()
          this.form.contactPostion = val.map((item) => item.postion).join()
          this.form.contactTelephone = val.map((item) => {
              if (item.telephone !== '' && item.wechat !== '') {
                return item.telephone + '/' + item.wechat
              }
              if (item.telephone !== '') {
                return item.telephone
              }
              if (item.wechat !== '') {
                return item.wechat
              }
            }).join()
        }
      },
      handleSelectDistributorContact() {
        this.$refs.selectDistributorContact.open()
      },
      selectDistributorContact(val) {
        if (val && val.length > 0) {
          this.form.dealerSalesId = val[0].id
          this.form.dealerSalesName = val.map((item) => item.name).join()
          this.form.dealerSalesContact = val
            .map((item) => {
              if (item.phone !== '' && item.wechat !== '') {
                return item.phone + '/' + item.wechat
              }
              if (item.phone !== '') {
                return item.phone
              }
              if (item.wechat !== '') {
                return item.wechat
              }
            })
            .join()
        }
      },
      // 业务调级（升级、降级）
      handleClick(type) {
        this.form.id = this.busId
        this.form = Object.assign(this.form, this.businessInfo)
        if (type === 'up') {
          this.title = '升级'
          if (this.form.nboType === '50') {
            this.form.nboType = '30'
          }
          if (this.form.nboType === '30') {
            this.form.nboType = '20'
          }
          if (this.form.nboType === '20') {
            this.form.nboType = '10'
          }
        }
        if (type === 'down') {
          this.title = '降级'
          if (this.form.nboType === '30') {
            this.form.nboType = '50'
          }
          if (this.form.nboType === '20') {
            this.form.nboType = '30'
          }
          if (this.form.nboType === '10') {
            this.form.nboType = '20'
          }
        }
        this.type = type
        this.form.isAdoptDashoo = '20'
        this.customerInfo = { custId: this.form.custId, custName: this.form.custName }
        this.queryCustomerContact = { custId: this.form.custId }
        this.distInfo = { distId: this.form.distributorId, distName: this.form.distributorName }
        this.queryDistContact = { distId: this.form.distributorId }
        this.productData = this.form.products || []
        if (this.form.quotationFileList) {
          this.quotationFileList = this.form.quotationFileList.map((item) => {
            this.form.quotationFile = item.fileUrl
            return { name: item.fileName, url: item.fileUrl }
          })
        }
        this.dialogFormVisible = true
        this.$nextTick(() => this.$refs['form'].clearValidate())
      },
      open(row) {
        this.form.id = row.id
        this.form = Object.assign(this.form, row)
        this.dialogFormVisible = true
        this.loading = false
        this.$refs['form'].clearValidate()
      },
      close() {
        this.$refs['form'].resetFields()
        this.$refs['form'].clearValidate()
        this.form = this.$options.data().form
        this.productData = []
        this.quotationFileList = []
        this.dashooParamFileList = []
        this.dialogFormVisible = false
        this.loading = false
      },
      save() {
        this.form.products = this.productData
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            this.$baseConfirm('你确定要对当前项目' + this.title + '吗', null, async () => {
              this.loading = true
              let err, res
              if (this.type === 'up') {
                ;[err, res] = await to(businessApi.businessUpgrade(this.form))
              }
              if (this.type === 'down') {
                ;[err, res] = await to(businessApi.businessDowngrade(this.form))
              }
              if (err) {
                this.$baseMessage(res.msg, 'error')
              } else {
                this.$baseMessage(res.msg, 'success')
              }
              this.loading = false
              this.$emit('fetch-data')
              this.close()
            })
          }
        })
      },
    },
  }
</script>
<style lang="scss" scoped>
  .el-form-item--small.el-form-item {
    margin-bottom: 10px;
  }

  .el-col-8 {
    height: 75px;
  }
</style>
