<template>
  <div>
    <a-form>
      <a-row :gutter="24">
        <!--零部件编号-->
        <a-col :lg='8' :md='24' :sm='24' :xl='8' :xs='24'>
          <a-form-item :label="$t('workbench.compoment-number')">
            <a-input v-model.trim="formData.partNo" :maxLength='128' :placeholder="$t('global-btn.please-enter') + $t('workbench.compoment-number')" allowClear/>
          </a-form-item>
        </a-col>
        <!--零部件名称-->
        <a-col :lg='8' :md='24' :sm='24' :xl='8' :xs='24'>
          <a-form-item :label="$t('workbench.compoment-name')">
            <a-input v-model.trim="formData.partName" :maxLength='128' :placeholder="$t('global-btn.please-enter') + $t('workbench.compoment-name')" allowClear/>
          </a-form-item>
        </a-col>
        <!-- CPAC编码 -->
        <a-col :lg='8' :md='24' :sm='24' :xl='8' :xs='24'>
          <a-form-item :label="$t('verity.dvp.cpac.number')">
            <a-select
              allowClear
              showSearch
              v-model="formData.cpacCode"
              :placeholder="$t('global-btn.please-select') + $t('verity.dvp.cpac.number')"
              :options="cpacList"
              :filterOption="handleCpacCodeFilterOption"
              @change="cpacChange"
              @search="getCpacInitData">
              <a-icon slot="suffixIcon" type="search" />
            </a-select>
          </a-form-item>
        </a-col>
        <!-- FND代码 -->
        <a-col :lg='8' :md='24' :sm='24' :xl='8' :xs='24'>
          <a-form-item :label="$t('verity.dvp.fnd.code')">
            <a-select
              allowClear
              showSearch
              v-model='formData.fndCode'
              :placeholder="$t('global-btn.please-select') + $t('verity.dvp.fnd.code')"
              :options="fndCodeList"
              :filterOption="handleFndCodeFilterOption"
              @search="getFndCodeList"
              @change="fndChange">
              <a-icon slot="suffixIcon" type="search" />
            </a-select>
          </a-form-item>
        </a-col>
        <!--试验项目-->
        <a-col :lg='8' :md='24' :sm='24' :xl='8' :xs='24'>
          <a-form-item :label="$t('plan.dvp.test-project')">
            <a-input v-model.trim="formData.testProject" :maxLength='500' :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.test-project')" allowClear/>
          </a-form-item>
        </a-col>
        <!-- 试验类型 -->
        <a-col :lg='8' :md='24' :sm='24' :xl='8' :xs='24'>
          <a-form-item :label="$t('plan.dvp.test-type')">
            <a-select v-model.trim="formData.testType" :options="testTypeList" :filter-option="handleFilterDataList" :placeholder="$t('global-btn.please-select') + $t('plan.dvp.test-type')" allowClear></a-select>
          </a-form-item>
        </a-col>
        <!--创建者-->
        <a-col :lg='8' :md='24' :sm='24' :xl='8' :xs='24'>
          <a-form-item :label="$t('plan.dvp.creator')">
            <a-input v-model.trim="formData.creator" :maxLength='50' :placeholder="$t('global-btn.please-enter') + $t('plan.dvp.creator')" allowClear></a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-form-item class='tr m15'>
          <a-col :lg='24' :md='24' :sm='24' :xl='24' :xs='24'>
            <!-- 重置 -->
            <a-button class="mr10" type="primary" @click='reset'>
              {{ $t('global-btn.reset') }}
            </a-button>
            <!-- 查询 -->
            <a-button class="mr10" type="primary" @click='search'>
              {{ $t('global-btn.search') }}
            </a-button>
          </a-col>
        </a-form-item>
      </a-row>
    </a-form>

    <a-table
      :columns='tableColumns'
      :dataSource='tableData'
      :pagination='pagination'
      :rowKey='(record, index) => { return record.templateTestId; }'
      :scroll='{x:1000, y: tableHeightValue }'
      size="small"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      @change='handlePageChange'
      bordered
      :components='components'
    >
      <!-- 序号列 -->
      <template slot='index' slot-scope='text, record, index'>
        <span>{{ (pagination.current - 1) * pagination.pageSize + index + 1 }}</span>
      </template>
      <!-- 试验来源 -->
      <template slot='testSource' slot-scope='text, record'>
        <span>{{ testSourceMap[record.testSource] || '-' }}</span>
      </template>
      <!-- 试验类型 -->
      <template slot='testType' slot-scope='text, record'>
        <span>{{ testTypeMap[record.testType] || '-' }}</span>
      </template>
    </a-table>
    <a-form>
      <a-row :gutter="24">
        <!-- 变更原因 -->
        <a-col :lg='16' :md='24' :sm='24' :xl='24' :xs='24' v-if="applyButtonFlag">
          <a-form-item required :label="$t('base.info.change-reason')">
            <a-textarea
              v-model.trim="changeReason"
              :placeholder="$t('base.info.please-enter-change-reason')"
              allowClear
              :auto-size="{ minRows: 3, maxRows: 5 }"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </div>
</template>
<script>

import VueDraggableResizable from 'vue-draggable-resizable';

export default {
  components: {
    VueDraggableResizable
  },
  props: {
    /** 变更申请按钮显示隐藏 */
    applyButtonFlag: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    this.components = {
			header: {
				cell: (h, props, children) => {
					const { key, ...restProps } = props;
					// 此处的this.columns 是定义的table的表头属性变量
					const col = this.tableColumns.find((col) => {
						const k = col.dataIndex || col.key;
						return k === key;
					});
					if (!col || !col.width) {
						return h('th', { ...restProps }, [...children]);
					}
					const dragProps = {
						key: col.dataIndex || col.key,
						class: 'table-draggable-handle',
						attrs: {
							w: 10,
							x: col.width,
							z: 1,
							axis: 'x',
							draggable: true,
							resizable: false
						},
						on: {
							dragging: (x, y) => {
								col.width = Math.max(x, 90);
							}
						}
					};
					const drag = h('vue-draggable-resizable', { ...dragProps });
					return h('th', { ...restProps, class: 'resize-table-th' }, [...children, drag]);
				}
			}
		};
    return {
      changeReason: undefined, // 变更原因
      /** 查询数据 */
      formData: {
        cpacId: undefined,
        fndId: undefined
      },
      /** 表格高度 */
      tableHeight: window.innerHeight - 352 + 'px',
      tableHeightValue: window.innerHeight - 352,
      /** 表格数据 */
      tableData: [],
      /** 表格列 */
      tableColumns: [
        //序号
        {
          title: this.$t('plan.dvp.serial-number'),
          dataIndex: 'index',
          width: 100,
          fixed: 'left',
          align: 'center',
          scopedSlots: {
            customRender: 'index'
          },
          ellipsis: true
        },
        // 零部件编号
        {
          title: this.$t('workbench.compoment-number'),
          dataIndex: 'partCode',
          width: 100,
          align: 'center',
          ellipsis: true
        },
        // 零部件名称
        {
          title: this.$t('workbench.compoment-name'),
          dataIndex: 'partName',
          width: 100,
          align: 'center',
          ellipsis: true
        },
        // CPAC编码
        {
          title: this.$t('base.info.CPAC-code'),
          dataIndex: 'cpacCode',
          width: 100,
          align: 'center',
          ellipsis: true
        },
        // FND代码
        {
          title: this.$t('plan.dvp.fnd-code'),
          dataIndex: 'fndCode',
          width: 100,
          align: 'center',
          ellipsis: true
        },
        // 创建者
        {
          title: this.$t('plan.dvp.creator'),
          dataIndex: 'creator',
          width: 100,
          align: 'center',
          ellipsis: true
        },
        // 试验类型
        {
          title: this.$t('plan.dvp.test-type'),
          dataIndex: 'testType',
          width: 100,
          align: 'center',
          scopedSlots: {
            customRender: 'testType'
          },
        },
        // 试验项目
        {
          title: this.$t('plan.dvp.test-project'),
          dataIndex: 'testProject',
          width: 100,
          align: 'center',
          ellipsis: true
        },
        // 试验来源
        {
          title: this.$t('plan.dvp.test-source'),
          dataIndex: 'testSource',
          width: 100,
          align: 'center',
          scopedSlots: {
            customRender: 'testSource'
          },
        },
        // 开发目标要求（接受标准）
        {
          title: this.$t('base.info.development-objective-requirements'),
          dataIndex: 'targetRequire',
          width: 110,
          align: 'center',
          ellipsis: true
        },
        // 试验标准和试验方法
        {
          title: this.$t('plan.dvp.test-standards-and-test-method'),
          dataIndex: 'testStandard',
          width: 150,
          align: 'center',
          ellipsis: true
        },
        // 测试阶段
        {
          title: this.$t('plan.dvp.test-step'),
          dataIndex: 'testStep',
          width: 100,
          align: 'center',
          ellipsis: true
        },
        // 测试次数
        {
          title: this.$t('plan.dvp.test-count'),
          dataIndex: 'testFrequency',
          width: 100,
          align: 'center',
          ellipsis: true
        }
      ],
      /** 分页 */
      pagination: {
        size: 'small',
        current: 1,
        pageNo: 1,
        pageSize: 10, // 默认每页显示数量
        showTotal: total => this.$t('global-constant.table.show-total', {total: `${total}`}), // 显示总数
        showSizeChanger: true, // 显示可改变每页数量
        pageSizeOptions: ['10', '20', '50', '100', '200'], // 每页数量选项
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize), // 改变每页数量时更新显示
        total: 0, //总条数
        showQuickJumper: true,
      },
      /** 试验来源Map 用于表格插槽显示 */
      testSourceMap: {
        '1': this.$t('dvp.drawing'),
        '2': this.$t('dvp.KPC'),
        '3': this.$t('dvp.web-require'),
        '4': this.$t('dvp.standard'),
        '5': this.$t('dvp.laws-and-regulations')
      },
      testTypeMap: {
        '1': this.$t('dvp.appearance'),
        '2': this.$t('dvp.size'),
        '3': this.$t('dvp.material-regulations'),
        '4': this.$t('dvp.performance-and-functionality'),
        '5': this.$t('dvp.vehicle-installation-verification')
      },
      /** 试验类型字典  未确定具体字段-暂时写死*/
      testTypeList: [
        {
          value: '1',
          label: this.$t('dvp.appearance')
        },
        {
          value: '2',
          label: this.$t('dvp.size')
        },
        {
          value: '3',
          label: this.$t('dvp.material-regulations')
        },
        {
          value: '4',
          label: this.$t('dvp.performance-and-functionality')
        },
        {
          value: '5',
          label: this.$t('dvp.vehicle-installation-verification')
        }
      ],
      /** cpac */
      cpacList: [],
      /** fnd */
      fndCodeList: [],
      /** 表格选中行的key 默认是index */
      selectedRowKeys: [],
      /** 表格选中行数据 */
      selectedRow: [],
      /** 零件ID */
      partId : undefined
    }
  },
  mounted() {
    window.onresize = () => {
      this.tableHeight = window.innerHeight - 352 + 'px';
      this.tableHeightValue = window.innerHeight - 352;
    };
    this.getDefaultData();
    this.getCpacInitData();
    this.getFndCodeList();
  },
  methods: {
    // 获取默认值 调用初始化方法
    getDefaultData() {
      this.formData.partNo = this.$route.query.partNo;
      this.formData.partName = this.$route.query.partName;
      let cpacCode = this.$route.query.cpacCode;
      let fndCode = this.$route.query.fndCode;
      this.$api.getCpacInfoList({
        cpacCoding: cpacCode,
        cpacCn: cpacCode
      }).then(res => {
        if (res.flag) {
          let cpacData = res.data || [];
          this.formData.cpacCode = cpacData[0].cpacCoding + ' ' + cpacData[0].cpacCn
          this.formData.cpacId = cpacData[0].cpacId
        }
      }).finally(() => {
        this.$api.getFndInfoList({
          fndCode: fndCode ? fndCode.toString() : '',
          fndCn: fndCode ? fndCode.toString() : '',
          cpacId: this.formData.cpacId
        }).then(res => {
          if (res.flag) {
            let fndData = res.data || [];
            if (fndData.length > 0) {
              this.formData.fndCode = fndData[0].fndCode + ' ' + fndData[0].fndCn;
              this.formData.fndId = fndData[0].id;
            }
          }
        }).finally(() => {
          this.initData();
        });
      });
    },
    /**
     * 初始化表格方法
     */
    initData() {
      let data = {
        dvpId: this.$store.getters.dvpId,
        creator: this.formData.creator,
        partCode: this.formData.partNo,
        partName: this.formData.partName,
        testProject: this.formData.testProject,
        testType: this.formData.testType,
        cpacId: this.formData.cpacId,
        fndId: this.formData.fndId,
        templateTestIds: this.selectedRowKeys,
        pagination: {
          pageSize: this.pagination.pageSize,
          pageCurrent: this.pagination.current
        }
      };
      this.$api.initTemplateList(data).then(res => {
        if (res.flag) {
          this.tableData = res.data.data || [];
          this.pagination.total = res.data.total;
        } else {
          this.tableData = [];
          this.$notification.error({message: res.message});
        }
      });
    },
    /**
     * 下拉选模糊查询
     * @param input
     * @param option
     * @returns {boolean}
     */
     handleFilterDataList(input,option) {
      return option.componentOptions.children[0].text.toLowerCase().includes(input.toLowerCase());
    },
    /**
     * 初始化CPAC下拉列表
     */
     getCpacInitData(cpacCoding) {
      let _that = this;
      _that.$api.getCpacInfoList({
        cpacCoding: cpacCoding,
        cpacCn: cpacCoding
      }).then(res => {
        if (res.flag) {
          let cpacData = res.data || [];
          _that.cpacList = [];
          if (cpacData.length > 0) {
            cpacData.forEach(item => {
              let temp = {
                key: item.cpacId,
                value: item.cpacId + '-' + item.cpacCoding + '-' + item.cpacCn,
                label: item.cpacCoding + ' ' + item.cpacCn
              };
              _that.cpacList.push(temp);
            });
          }
        } else {
          _that.$notification.error({message: res.message});
        }
      });
    },
    /**
     * 获取FND代码下拉选数据
     */
     getFndCodeList(fndCode, cpacId) {
      let _that = this;
      _that.$api.getFndInfoList({
        fndCode: fndCode ? fndCode.toString() : '',
        fndCn: fndCode ? fndCode.toString() : '',
        cpacId: cpacId
      }).then(res => {
        if (res.flag) {
          let fndData = res.data || [];
          _that.fndCodeList = [];
          if (fndData.length > 0) {
            fndData.forEach(item => {
              let temp = {
                key: item.id,
                value: item.id + item.fndCode + ' ' + item.fndCn,
                label: item.fndCode + ' ' + item.fndCn
              };
              _that.fndCodeList.push(temp);
            });
          }
        } else {
          _that.$notification.error({message: res.message});
        }
      });
    },
    /**
     * cpac编码过滤配置
     * @param input
     * @param option
     * @returns {boolean}
     */
     handleCpacCodeFilterOption(input, option) {
      return (option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0);
    },
    /**
     * fnd编码过滤配置
     * @param input
     * @param option
     * @returns {boolean}
     */
     handleFndCodeFilterOption(input, option) {
      return (option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0);
    },
    /**
     * CPAC选择事件
     * @param value
     * @param options
     * @constructor
     */
     cpacChange(value, options) {
      this.formData.fndCode = undefined;
      this.formData.fndId = undefined;
      this.formData.cpacId = options ? options.data.key : undefined;
      this.$forceUpdate();
      this.getFndCodeList(null, this.formData.cpacId);
    },

    /**
     * FND选择事件
     * @param value
     * @param options
     * @constructor
     */
    fndChange(value, options) {
      this.formData.fndId = options ? options.data.key : undefined;
      this.$forceUpdate();
    },
    /**
     * 非空校验 判断是否为空
     * @returns {boolean}
     */
    isNull() {
      let _that = this;
      let message = [];
      // 请选择模板
      if (_that.selectedRowKeys.length === 0) {
        message.push(_that.$t('plan.dvp.please_select-template-item'));
      }
      // 变更原因
      if (_that.applyButtonFlag) {
        if (!_that.changeReason) {
          message.push(_that.$t('global-constant.please-enter') + _that.$t('base.info.change-reason'));
        }
      }
      if (message && message.length > 0) {
        for (let i = 0; i < message.length; i++) {
          _that.$notification.warning({message: message[i]});
        }
        return false;
      }
      return true;
    },

    /**
     * 保存
     */
    saveTemplateEdit() {
      // 非空校验
      if (!this.isNull()) {
        return false;
      }
      let data = {
        dvpId: this.$store.getters.dvpId,
        partId: this.partId,
        templateTestIds: this.selectedRowKeys,
        changeReason: this.changeReason
      };
      this.$api.templateBatchSave(data).then( res => {
        if (res.flag) {
          this.$message.success(res.message);
          this.selectedRowKeys = [];
          this.$emit("cancelEditDvp");
          this.$emit("initData")
        } else {
          this.$message.error(res.message);
        }
      });
    },

    /**
     * 搜索模块按钮-查询
     */
    search() {
      this.initData();
    },

    /**
     * 搜索模块按钮-重置
     */
    reset() {
      this.formData = {};
      this.pagination.current = 1;
      this.pagination.pageSize = 10;
      this.initData();
      this.getCpacInitData();
      this.getFndCodeList();
    },

    /**
     * 表格选中行事件
     * @param selectedRowKeys
     */
    onSelectChange(selectedRowKeys,selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRow = selectedRows;
    },

    /**
     * 表格 - 点击分页中数字触发的方法
     * @param pagination
     */
    handlePageChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.pagination.pageNo = pagination.current;
      this.initData();
    },
  }
}

</script>

<style lang="less" scoped>

</style>
