<template>
  <div style="display: inline-block; margin: 0 10px">
    <el-button
      v-permissions="['proj:business:upgrade']"
      :disabled="!['20', '30'].includes(businessInfo.nboType) || businessInfo.approStatus === '20'"
      type="primary"
      @click="handleClick('up')">
      升级
    </el-button>
    <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 ref="form" :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' && businessInfo.nboType === '10'" label="储备" value="50" />
          </el-select>
        </el-form-item>
        <!--   C-B     项目预算 经销商/代理商 技术支持时间 技术支持人员 技术支持内容 总部对接人 项目预算期限 资金来源 产品/方案满足情况-->
        <el-row v-if="type === 'up' && 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>
          <el-col :span="8">
            <el-form-item label="经销商/代理商" prop="distributorName">
              <el-input v-model="form.distributorName" readonly @focus="handleSelectDistributor" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总部对接人" prop="parentReceiver">
              <el-input v-model="form.parentReceiver" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="技术支持人员" prop="technicalSupportName" :required="type === 'up'">
              <el-input v-model="form.technicalSupportName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="技术支持内容" prop="technicalSupportContent">
              <el-input v-model="form.technicalSupportContent" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="技术支持时间" prop="technicalSupportTime" :required="type === 'up'">
              <el-date-picker
                v-model="form.technicalSupportTime"
                placeholder="选择日期"
                style="width: 100%"
                type="datetime" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="type === 'up' && form.nboType !== '30'" :gutter="20">
          <el-col :span="8">
            <el-form-item label="项目预算期限" prop="nboBudgetTime">
              <el-date-picker v-model="form.nboBudgetTime" placeholder="选择日期" style="width: 100%" type="datetime" />
            </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="productSatisfaction">
              <el-input v-model="form.productSatisfaction" />
            </el-form-item>
          </el-col>
        </el-row>
        <!--    B-A    采购方式	采购时间	是否采纳大数技术参数（上传附件）	决策部门	决策人员	经销商与客户历史成交信息	经销商销售人员	维护部门及人员-->
        <el-row v-if="type === 'up' && form.nboType === '10'" :gutter="20">
          <el-col :span="8">
            <el-form-item label="采购方式" prop="purchasingWay">
              <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="purchasingTime">
              <el-date-picker
                v-model="form.purchasingTime"
                placeholder="选择日期"
                style="width: 100%"
                type="datetime" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="决策人员" prop="makerName">
              <el-input v-model="form.makerName" readonly @focus="handleSelectContact" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="决策部门" prop="makerDept">
              <el-input v-model="form.makerDept" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="经销商与客户历史成交信息" prop="historicalTransactionInfo">
              <el-input v-model="form.historicalTransactionInfo" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="经销商销售人员" prop="dealerSalesName">
              <el-input v-model="form.dealerSalesName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="维护部门及人员" prop="accendant">
              <el-input v-model="form.accendant" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否采纳大数技术参数   " prop="isAdoptDashoo">
              <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-row>

        <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-form>
      <template #footer>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 选择客户决策人弹窗 -->
    <select-contact
      ref="selectContact"
      :default-customer="customerInfo"
      :query-params="queryContact"
      @save="selectContact" />
    <!-- 选择经销商弹窗 -->
    <select-distributor ref="selectDistributor" @save="selectDistributor" />
  </div>
</template>

<script>
  import businessApi from '@/api/proj/business'
  import AmountInput from '@/components/currency/index.vue'
  import SelectContact from '@/components/select/SelectCustomerContact'
  import SelectDistributor from '@/components/select/SelectDistributor'

  export default {
    name: 'BusinessGradation',
    components: {
      AmountInput,
      SelectContact,
      SelectDistributor,
    },
    props: {
      // 项目Id
      busId: {
        type: Number,
        required: true,
      },
      // 项目类别
      businessInfo: {
        type: Object,
        required: true,
      },
    },
    data() {
      const validateTechnicalSupport = (rule, value, callback) => {
        if (!value && this.type === 'up') callback(new Error('不能为空'))
        else callback()
      }
      return {
        title: '项目',
        type: '',
        form: {
          id: undefined,
          distributorId: undefined,
          distributorName: undefined,
          makerId: undefined,
          makerName: undefined,
          makerDept: undefined,
          makerPost: undefined,
          makerTelephone: undefined,
          nboType: undefined,
          nboBudget: undefined,
          technicalSupportName: undefined,
          technicalSupportContent: undefined,
          technicalSupportTime: undefined,
          parentReceiver: undefined,
          nboBudgetTime: undefined,
          capitalSource: undefined,
          productSatisfaction: undefined,
          purchasingWay: undefined,
          purchasingTime: undefined,
          isAdoptDashoo: undefined,
          historicalTransactionInfo: undefined,
          dealerSalesId: undefined,
          dealerSalesName: undefined,
          accendant: undefined,
          remark: undefined,
        },
        rules: {
          nboType: [{ required: true, trigger: ['blur', 'change'], message: '请选择项目级别' }],
          nboBudget: [{ required: true, trigger: ['blur', 'change'], message: '请输入项目预算' }],
          distributorName: [{ required: true, trigger: ['blur', 'change'], message: '请选择经销商/代理商' }],
          technicalSupportName: [
            { validator: validateTechnicalSupport, trigger: ['blur', 'change'], message: '请输入技术支持人员' },
          ],
          technicalSupportContent: [{ required: true, trigger: ['blur', 'change'], message: '请输入技术支持内容' }],
          technicalSupportTime: [
            { validator: validateTechnicalSupport, trigger: ['blur', 'change'], message: '请选择技术支持时间' },
          ],
          remark: [{ required: true, trigger: ['blur', 'change'], message: '请输入原因' }],
        },
        dialogFormVisible: false,
        yesOrNoOptions: [],
        purchasingWayOptions: [],

        queryContact: {},
        customerInfo: {},
      }
    },
    mounted() {
      this.getDicts('proj_purchasing_way').then((response) => {
        this.purchasingWayOptions = response.data.values || []
      })
    },
    methods: {
      handleSelectContact() {
        if (!this.queryContact.custId) {
          this.$message.warning('请先选择客户')
          return
        }
        this.$refs.selectContact.open()
      },
      selectContact(val) {
        if (val && val.length > 0) {
          this.form.makerId = val[0].id
          this.form.makerName = val.map((item) => item.cuctName)
          this.form.makerDept = val.map((item) => item.makerDept)
          this.form.makerPost = val.map((item) => item.postion)
          this.form.makerTelephone = val.map((item) => item.telephone)
        }
      },
      handleSelectDistributor() {
        this.$refs.selectDistributor.open()
      },
      selectDistributor(val) {
        if (val && val.length > 0) {
          this.form.distributorId = val[0].id
          this.form.distributorName = val.map((item) => item.distName).join()
        }
      },
      // 业务调级（升级、降级）
      handleClick(type) {
        if (type === 'up') {
          this.title = '升级'
        }
        if (type === 'down') {
          this.title = '降级'
        }
        this.type = type
        this.form.id = this.busId
        this.form = Object.assign(this.form, this.businessInfo)
        this.form.nboType = undefined
        this.form.technicalSupportName = undefined
        this.form.technicalSupportContent = undefined
        this.form.technicalSupportTime = undefined
        this.form.remark = undefined
        console.log(this.form)
        this.dialogFormVisible = true
      },
      open(row) {
        this.form.id = row.id
        this.form = Object.assign(this.form, row)
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            this.$baseConfirm('你确定要对当前项目' + this.title + '吗', null, async () => {
              if (this.type === 'up') {
                const { msg } = await businessApi.businessUpgrade(this.form)
                this.$baseMessage(msg, 'success')
              }
              if (this.type === 'down') {
                const { msg } = await businessApi.businessDowngrade(this.form)
                this.$baseMessage(msg, 'success')
              }

              this.$emit('fetch-data')
              this.close()
            })
          }
        })
      },
    },
  }
</script>
<style lang="scss" scoped>
  .el-form-item--small.el-form-item {
    margin-bottom: 10px;
  }
</style>
