<template>
  <div class="">
    <el-form ref="dingtalkForm" label-position="top" :model="dingtalkForm">
      <el-row :gutter="20">
        <div v-for="(item, index) in dingtalkForm.items" :key="index">
          <el-col v-if="item.componentName !== 'TableField'" :span="colSpan">
            <el-form-item
              :label="item.props.label"
              :prop="'items.' + index + '.props.value'"
              :rules="{
                required: item.props.required,
                message: '不能为空',
                trigger: ['blur', 'change'],
              }">
              <!--文本框-->
              <el-input
                v-if="item.componentName === 'TextField'"
                v-model="item.props.value"
                :disabled="item.props.disabled"
                :placeholder="item.props.placeholder" />
              <!--文本域-->
              <el-input
                v-else-if="item.componentName === 'TextareaField'"
                v-model="item.props.value"
                :disabled="item.props.disabled"
                :placeholder="item.props.placeholder"
                :rows="5"
                show-word-limit
                type="textarea" />
              <!--下拉选-->
              <el-select
                v-else-if="item.componentName === 'DDSelectField'"
                v-model="item.props.value"
                clearable
                :disabled="item.props.disabled"
                :placeholder="item.props.placeholder"
                style="width: 100%">
                <el-option
                  v-for="option in selectDataToJson(item.props.options)"
                  :key="option.key"
                  :label="option.value"
                  :value="option.value" />
              </el-select>
              <!--下拉多选-->
              <el-select
                v-else-if="item.componentName === 'DDMultiSelectField'"
                v-model="item.props.value"
                clearable
                :disabled="item.props.disabled"
                multiple
                :placeholder="item.props.placeholder"
                style="width: 100%">
                <el-option
                  v-for="option in selectDataToJson(item.props.options)"
                  :key="option.key"
                  :label="option.value"
                  :value="option.value" />
              </el-select>
              <!--时间选择器-->
              <el-date-picker
                v-else-if="item.componentName === 'DDDateField'"
                v-model="item.props.value"
                :disabled="item.props.disabled"
                :placeholder="item.props.placeholder"
                type="daterange"
                :value-format="item.props.format" />
              <!--时间范围选择器-->
              <el-date-picker
                v-else-if="item.componentName === 'DDDateRangeField'"
                v-model="item.props.value"
                :disabled="item.props.disabled"
                :end-placeholder="item.props.placeholder[1]"
                :start-placeholder="item.props.placeholder[0]"
                style="width: 100%"
                type="daterange"
                :value-format="item.props.format" />

              <!--文件-->
              <el-upload
                v-else-if="item.componentName === 'DDAttachment'"
                :ref="item.props.id"
                action="#"
                :auto-upload="false"
                :file-list="item.props.value"
                :limit="1"
                :on-change="
                  (file) => {
                    return setFile(index, file)
                  }
                ">
                <el-button size="mini" type="primary">点击上传</el-button>
              </el-upload>

              <!--选择用户-->
              <el-input
                v-else-if="item.componentName === 'InnerContactField'"
                v-model="item.props.value"
                :disabled="item.props.disabled"
                :placeholder="item.props.placeholder"
                readonly
                suffix-icon="el-icon-search"
                @focus="handleSelectUser(index)" />
            </el-form-item>
          </el-col>

          <el-col v-if="item.componentName === 'TableField'" :span="24">
            <el-form-item :label="item.props.label" :prop="item.props.id" :required="item.props.required">
              <el-button
                v-show="item.props.actionName"
                style="float: right; margin-top: -20px"
                @click="addTableData(index)">
                {{ item.props.actionName }}
              </el-button>
              <!--表格-->
              <el-table :key="dingTableFlag" :ref="'dingTable' + index" border :data="item.tableData" height="250px">
                <el-table-column
                  v-for="(child, idx) in item.children"
                  :key="idx"
                  align="center"
                  :label="child.props.label"
                  :prop="child.props.id"
                  show-overflow-tooltip>
                  <template #default="{ row }">
                    <!--文本框-->
                    <el-select
                      v-if="child.props.label === '产品型号'"
                      v-model="row[child.props.id]"
                      filterable
                      :placeholder="item.props.placeholder"
                      value-key="prodCode"
                      @change="(val) => selectLabel(val, item.children, row)">
                      <el-option v-for="prod in productList" :key="prod.id" :label="prod.prodCode" :value="prod" />
                    </el-select>
                    <el-select
                      v-if="child.props.label === '产品名称'"
                      v-model="row[child.props.id]"
                      filterable
                      :placeholder="item.props.placeholder"
                      value-key="prodName"
                      @change="(val) => selectLabel(val, item.children, row)">
                      <el-option v-for="prod in productList" :key="prod.id" :label="prod.prodName" :value="prod" />
                    </el-select>
                    <!--数字文本框-->
                    <el-input
                      v-if="child.componentName === 'NumberField'"
                      v-model="row[child.props.id]"
                      :min="1"
                      onkeyup="value=value.replace(/[^\d]/g,'')" />
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </div>
      </el-row>
    </el-form>

    <!-- 选择人员弹窗 -->
    <select-user ref="selectUser" @save="selectUser" />
  </div>
</template>

<script>
  import productApi from '@/api/base/product'
  import SelectUser from '@/components/select/SelectUser'

  export default {
    name: 'DingTalkFromToVue',
    components: {
      SelectUser,
    },
    props: {
      colSpan: {
        type: Number,
        default: 24,
      },
    },
    data() {
      return {
        dingtalkForm: {},
        fileList: [],
        productList: [],
        dingRules: {},
        userItemIndex: {},
        dingTableFlag: true,
      }
    },
    mounted() {
      this.getProduct()
    },
    // 方法集合
    methods: {
      selectLabel(val, children, row) {
        const codeId = children.find((item) => item.props.label == '产品型号').props.id
        const nameId = children.find((item) => item.props.label == '产品名称').props.id
        row[codeId] = val.prodCode
        row[nameId] = val.prodName
      },
      getProduct() {
        let params = {
          pageNum: 1,
          pageSize: 999,
        }
        Promise.all([productApi.getList({ ...params })])
          .then(([product]) => {
            this.productList = product.data.list || []
          })
          .catch((err) => console.log(err))
      },
      addTableData(index) {
        let newObj = {}
        let tableData = this.dingtalkForm.items[index].tableData
        if (!tableData) {
          this.dingtalkForm.items[index].tableData = []
        }
        for (let child of this.dingtalkForm.items[index].children) {
          newObj[child.props.id] = ''
        }
        this.dingtalkForm.items[index].tableData.push(newObj)
        this.dingTableFlag = !this.dingTableFlag
      },
      handleSelectUser(index) {
        this.userItemIndex = index
        this.$refs.selectUser.open()
      },
      selectUser(val) {
        let nickName = val.map((item) => item.nickName).join()
        this.dingtalkForm.items[this.userItemIndex].props.value = nickName
        this.$forceUpdate()
      },
      // 文件
      setFile(index, file) {
        this.$emit('upload', file.raw)
        this.dingtalkForm.items[index].props.value = file.name
        // 上传文件一直校验不过问题方案
        let temp = JSON.parse(JSON.stringify(this.dingtalkForm))
        this.$refs.dingtalkForm.clearValidate('items.' + index + '.props.value')
        this.dingtalkForm = temp
        return true
      },
      selectDataToJson(data) {
        return data.map((item) => {
          return JSON.parse(item)
        })
      },
      setFormAndRules(dingtalkForm) {
        for (let index in dingtalkForm.items) {
          if (dingtalkForm.items[index].componentName === 'DDDateRangeField') {
            dingtalkForm.items[index].props.placeholder = JSON.parse(dingtalkForm.items[index].props.label)
            dingtalkForm.items[index].props.label = dingtalkForm.items[index].props.placeholder.join(' - ')
          }
        }
        this.dingtalkForm = dingtalkForm
      },
      getFormData() {
        for (let index in this.dingtalkForm.items) {
          // 表格数据需要特殊处理
          if (this.dingtalkForm.items[index].componentName === 'TableField') {
            this.dingtalkForm.items[index].props.value = []
            let tableData = this.dingtalkForm.items[index].tableData
            for (let row of tableData) {
              // 循环数据，组装信息
              let newData = []
              for (let colKey in row) {
                let child = this.dingtalkForm.items[index].children.find((val) => {
                  return val.props.id === colKey //筛选出匹配数据
                })
                newData.push({
                  value: row[colKey],
                  id: child.props.id,
                  name: child.props.label,
                  required: child.props.required,
                  componentName: child.componentName,
                })
              }
              this.dingtalkForm.items[index].props.value.push(newData)
            }
          }
        }
        return this.dingtalkForm
      },
      validateForm() {
        let result = false
        this.$refs['dingtalkForm'].validate((valid) => {
          result = valid
        })
        return result
      },
      resetForm() {
        this.$refs['dingtalkForm'].resetFields()
      },
    },
  }
</script>

<style lang="scss" scoped></style>
