<!-- eslint-disable vue/no-mutating-props -->
<template>
  <el-dialog append-to-body title="添加" :visible.sync="selfVisible" @close="close" @open="open">
    <el-form ref="form" :model="form" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="标题" prop="taskTitle">
            <el-input v-model="form.taskTitle" placeholder="请输入标题" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="类型" prop="taskType">
            <el-select v-model="form.taskType" placeholder="请选择类型" style="width: 100%">
              <el-option v-for="item in types" :key="item.dictCode" :label="item.dictLabel" :value="item.dictValue" />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="开始时间" prop="taskStartDate">
            <el-date-picker
              v-model="form.taskStartDate"
              placeholder="请选择开始时间"
              style="width: 100%"
              type="date"
              value-format="yyyy-MM-dd HH:mm:ss" />
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="要求完成时间" prop="taskEndDate">
            <el-date-picker
              v-model="form.taskEndDate"
              placeholder="请选择要求完成时间"
              style="width: 100%"
              type="date"
              value-format="yyyy-MM-dd HH:mm:ss" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="事项来源" prop="source">
            <el-select v-model="form.source" placeholder="请选择事项来源" style="width: 100%">
              <el-option v-for="item in sourceOptions" :key="item.key" :label="item.value" :value="item.key" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="督办内容" prop="taskDesc">
            <el-input v-model="form.taskDesc" placeholder="请输入督办内容" type="textarea" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责人" prop="mainUserId">
            <!-- <el-select v-model="form.mainUserId" placeholder="请选择负责人" style="width: 100%">
              <el-option v-for="item in users" :key="item.id" :label="item.userName" :value="item.id" />
            </el-select> -->
            <el-input v-model="form.mainUserName" placeholder="负责人" readonly>
              <el-button slot="append" icon="el-icon-search" @click="choose(false, 'mainUserId', 'mainUserName')" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="督办人" prop="supervisorUserId">
            <!-- <el-select v-model="form.supervisorUserId" placeholder="请选择督办人" style="width: 100%">
              <el-option v-for="item in users" :key="item.id" :label="item.userName" :value="item.id" />
            </el-select> -->
            <el-input v-model="form.supervisorUserName" readonly>
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="choose(false, 'supervisorUserId', 'supervisorUserName')" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="协办人" prop="teamNames">
            <!-- <el-select v-model="teamIds" clear multiple placeholder="请选择协办人" style="width: 100%">
              <el-option v-for="item in users" :key="item.id" :label="item.userName" :value="item.id" />
            </el-select> -->
            <el-input v-model="form.teamNames" placeholder="协办人" readonly>
              <el-button slot="append" icon="el-icon-search" @click="choose(true, 'teamIds', 'teamNames')" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="监办人" prop="watchUserId">
            <!-- <el-select v-model="form.watchUserId" clear placeholder="请选择监办人" style="width: 100%">
              <el-option v-for="item in users" :key="item.id" :label="item.userName" :value="item.id" />
            </el-select> -->
            <el-input v-model="form.watchUserName" placeholder="监办人" readonly>
              <el-button slot="append" icon="el-icon-search" @click="choose(false, 'watchUserId', 'watchUserName')" />
            </el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="关联类型" prop="targetType">
            <el-select
              v-model="form.targetType"
              placeholder="请选择关联对象类型"
              style="width: 100%"
              @change="targetTypeChange">
              <el-option label="客户" value="10" />
              <el-option label="项目" value="20" />
              <el-option label="合同" value="30" />
              <el-option label="回款" value="40" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关联对象" prop="targetId">
            <el-select
              v-model="form.targetId"
              filterable
              placeholder="请选择关联对象"
              style="width: 100%"
              @change="targetChange">
              <el-option v-for="item in targets" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" />
          </el-form-item>
        </el-col> -->
      </el-row>
    </el-form>
    <template #footer>
      <!-- eslint-disable-next-line vue/no-mutating-props -->
      <el-button @click="selfVisible = false">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
    <SelectUser
      ref="selectUser"
      :ids="ids"
      :label="label"
      :multiple="multiple"
      :property="property"
      @save="selectUser" />
  </el-dialog>
</template>

<script>
  import SelectUser from '@/components/select/SelectUser.vue'
  import taskApi from '@/api/plat/task'
  import custApi from '@/api/customer/index'
  import businessApi from '@/api/proj/business'
  import contractApi from '@/api/contract'
  import collectionApi from '@/api/contract/collection'

  export default {
    name: 'TaskAdd',
    components: {
      SelectUser,
    },
    props: {
      users: {
        type: Array,
        default() {
          return []
        },
      },
      types: {
        type: Array,
        default() {
          return []
        },
      },
      doRefresh: {
        type: Function,
        default: undefined,
      },
    },
    data() {
      return {
        // 项目数据
        projects: [],
        // 合同
        contracts: [],
        // 回款
        payments: [],
        selfVisible: false,
        // 协办人
        teamIds: [],
        // 客户数据
        customers: [],
        // 关联对象
        targets: [],
        // 新增数据表单
        form: {
          taskTitle: '',
          taskType: '',
          taskStatus: '10',
          isOverdue: '10',
          taskStartDate: '',
          taskEndDate: '',
          source: '',
          taskDesc: '',
          supervisorUserId: '',
          watchUserId: '',
          mainUserId: '',
          ownerUserId: '',
          taskLabel: '',
          targetId: '',
          targetType: '',
          targetName: '',
          remark: '',
          teamIds: [],
          teamNames: '',
          mainUserName: '',
          watchUserName: '',
          supervisorUserName: '',
        },
        // 校验规则
        rules: {
          taskTitle: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
          taskType: [{ required: true, message: '类型不能为空', trigger: 'blur' }],
          // taskStartDate: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
          taskEndDate: [{ required: true, message: '要求完成时间不能为空', trigger: 'blur' }],
          supervisorUserId: [{ required: true, message: '督办人不能为空', trigger: 'change' }],
          mainUserId: [{ required: true, message: '负责人不能为空', trigger: 'change' }],
          teamNames: [{ required: true, message: '协办人不能为空', trigger: 'change' }],
          watchUserId: [{ required: true, message: '监办人不能为空', trigger: 'change' }],
        },
        multiple: false,
        property: '',
        label: '',
        ids: [],
        sourceOptions: [],
      }
    },
    watch: {
      selfVisible(val) {
        this.$emit('update:selfVisible', val)
      },
    },
    mounted() {
      this.getOptions()
    },
    methods: {
      getOptions() {
        Promise.all([this.getDicts('plat_task_source')])
          .then(([source]) => {
            this.sourceOptions = source.data.values || []
          })
          .catch((err) => console.log(err))
      },
      // 关联类型变化
      targetTypeChange() {
        this.targets.splice(0, this.targets.length)
        this.form.targetId = ''
        this.form.targetName = ''
        if (this.form.targetType == '10') {
          for (let cust of this.customers) {
            this.targets.push(cust)
          }
        }
        if (this.form.targetType == '20') {
          for (let cust of this.projects) {
            this.targets.push(cust)
          }
        }
        if (this.form.targetType == '30') {
          for (let cust of this.contracts) {
            this.targets.push(cust)
          }
        }
        if (this.form.targetType == '40') {
          for (let cust of this.payments) {
            this.targets.push(cust)
          }
        }
      },
      // 关联对象变化
      targetChange() {
        for (let item of this.targets) {
          if (item.value == this.form.targetId) {
            this.form.targetName = item.label
            break
          }
        }
      },
      // 获取基本数据
      getData() {
        this.customers = []
        this.projects = []
        this.contracts = []
        this.payments = []
        custApi
          .getList({ targetType: '10', pageSize: 9999 })
          .then((res) => {
            if (res.data.list) {
              for (let cust of res.data.list) {
                let data = {
                  value: cust.id,
                  label: cust.custName,
                }
                this.customers.push(data)
              }
            }
          })
          .catch((err) => {
            console.error(err)
          })
        businessApi
          .getList({ pageSize: 9999 })
          .then((res) => {
            if (res.data.list) {
              for (let busi of res.data.list) {
                let data = {
                  value: busi.id,
                  label: busi.nboName,
                }
                this.projects.push(data)
              }
            }
          })
          .catch((err) => {
            console.error(err)
          })
        contractApi
          .getList({ pageSize: 9999 })
          .then((res) => {
            if (res.data.list) {
              for (let con of res.data.list) {
                let data = {
                  value: con.id,
                  label: con.contractName,
                }
                this.contracts.push(data)
              }
            }
          })
          .catch((err) => {
            console.error(err)
          })
        collectionApi
          .getList({ pageSize: 9999 })
          .then((res) => {
            if (res.data.list) {
              for (let pay of res.data.list) {
                let data = {
                  value: pay.id,
                  label:
                    '合同编号：' +
                    pay.contractCode +
                    ' 日期：' +
                    (pay.collectionDatetime ? pay.collectionDatetime.split(' ')[0] : '') +
                    ' 金额：' +
                    pay.collectionAmount,
                }
                this.payments.push(data)
              }
            }
          })
          .catch((err) => {
            console.error(err)
          })
      },
      // 打开弹窗
      open() {
        this.getData()
        if (this.$refs['form']) {
          this.$refs['form'].resetFields()
        }
        this.teamIds = []
        this.form.taskTitle = ''
        this.form.taskType = ''
        this.form.taskStatus = '10'
        this.form.isOverdue = '10'
        this.form.taskStartDate = ''
        this.form.taskEndDate = ''
        this.form.source = ''
        this.form.taskDesc = ''
        this.form.supervisorUserId = ''
        this.form.watchUserId = ''
        this.form.mainUserId = ''
        this.form.ownerUserId = ''
        this.form.taskLabel = ''
        this.form.targetId = ''
        this.form.targetType = ''
        this.form.targetName = ''
        this.form.remark = ''
        this.form.teamNames = ''
        this.form.mainUserName = ''
        this.form.watchUserName = ''
        this.form.supervisorUserName = ''
      },
      // 关闭弹窗
      close() {
        if (this.$refs['form']) {
          this.$refs['form'].resetFields()
        }
        // eslint-disable-next-line vue/no-mutating-props
        this.selfVisible = false
      },
      // 保存数据
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            if (this.form.teamIds && this.form.teamIds.length > 0) {
              this.form.ownerUserId = this.form.teamIds.join(',')
            } else {
              this.form.ownerUserId = ''
            }
            // eslint-disable-next-line vue/no-mutating-props
            this.selfVisible = false
            if (this.form.targetId == '') {
              this.form.targetId = 0
            }
            const { msg } = await taskApi.createTask(this.form)
            this.$baseMessage(msg, 'success', 'vab-hey-message-success')
            if (this.doRefresh) {
              this.doRefresh()
            }
          }
        })
      },
      choose(multiple, property, label) {
        this.multiple = multiple
        this.property = property
        this.label = label
        if (this.form[property].length) {
          this.$refs.selectUser.ids = this.form[property]
        } else if (this.form[property]) {
          this.$refs.selectUser.ids = [this.form[property]]
        } else {
          this.$refs.selectUser.ids = []
        }
        this.$refs.selectUser.open()
      },
      selectUser(userList, property, label) {
        this.form[label] = userList.map((item) => item.nickName).join()
        if (this.multiple) {
          this.form[property] = userList.map((item) => item.id)
        } else {
          this.form[property] = userList[0] ? userList[0].id : ''
        }
        this.$forceUpdate()
      },
    },
  }
</script>
