<template>
  <div class="ele-body">
    <!-- <el-card shadow="never" v-loading="loading"> -->
    <!-- 数据表格 -->
    <!-- :rules="[]" -->
    <el-form ref="form" :model="form" label-width="100px" class="create-form">
      <ele-pro-table
        ref="tableRef2"
        :columns="columnsDetail"
        :datasource="form.tableList"
        tool-class="ele-toolbar-form"
        :initLoad="false"
        :need-page="false"
        height="300px"
      >
        <template v-slot:toolbar>
          <div class="toobar" :class="buttonJud ? '' : 'toobar_r'">
            <el-button v-if="buttonJud" type="primary" @click="addBank"
              >添加</el-button
            >
            <span class="total_price">总计: {{ totalPrice }} (元)</span>
          </div>
        </template>
        <template v-slot:typeId="scope">
          <el-form-item
            style="margin-bottom: 20px"
            :prop="'tableList.' + scope.$index + '.typeId'"
          >
            <el-select
              v-model="scope.row.typeId"
              placeholder="请选择"
              class="w100"
              @change="typeIdChange(scope.row, scope.$index)"
              :disabled="schemeTableTool(scope.row)"
            >
              <!-- :disabled="type == 'view' || scope.row.isApply == 1" -->
              <el-option
                v-for="item in typeIdList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </template>
        <template v-slot:code="scope">
          <el-form-item
            style="margin-bottom: 20px"
            :prop="'tableList.' + scope.$index + '.code'"
          >
            <el-input
              v-if="scope.row.typeId != 2"
              :disabled="type == 'view'"
              v-model="scope.row.code"
            ></el-input>
            <span v-if="scope.row.typeId == 2">{{ scope.row.code }}</span>
          </el-form-item>
        </template>
        <template v-slot:name="scope">
          <el-form-item
            style="margin-bottom: 20px"
            :prop="'tableList.' + scope.$index + '.name'"
            :rules="{
              required: true,
              message:
                source == '配件回收'
                  ? '配件回收清单名称不能为空'
                  : '项目名称不能为空',
              trigger: 'change'
            }"
          >
            <!--:disabled="type == 'view' || scope.row.typeId == 2" -->
            <el-input
              :disabled="type == 'view' || scope.row.typeId == 2"
              v-model="scope.row.name"
              style="width: calc(100% - 62px)"
            ></el-input>
            <!--    scope.row.typeId == 2 &&
                scope.row.isApply != 1 &&
            type == 'edit'-->
            <el-button
              v-if="chooseShow(scope)"
              size="small"
              type="primary"
              style="margin-left: 4px"
              @click.native="addEquipment(row, scope.$index)"
              >选择</el-button
            >
          </el-form-item>
        </template>
        <template v-slot:categoryModel="scope">
          <el-form-item
            style="margin-bottom: 20px"
            :prop="'tableList.' + scope.$index + '.categoryModel'"
          >
            <el-input
              v-if="scope.row.typeId != 2"
              :disabled="type == 'view'"
              v-model="scope.row.categoryModel"
            ></el-input>
            <span v-if="scope.row.typeId == 2">
              {{ scope.row.categoryModel }}
            </span>
          </el-form-item>
        </template>
        <template v-slot:specification="scope">
          <el-form-item
            style="margin-bottom: 20px"
            :prop="'tableList.' + scope.$index + '.specification'"
          >
            <el-input
              v-if="scope.row.typeId != 2"
              :disabled="type == 'view'"
              v-model="scope.row.specification"
            ></el-input>
            <span v-if="scope.row.typeId == 2">
              {{ scope.row.specification }}
            </span>
          </el-form-item>
        </template>
        <template v-slot:content="scope">
          <el-form-item
            style="margin-bottom: 20px"
            :prop="'tableList.' + scope.$index + '.content'"
          >
            <el-input
              v-model="scope.row.content"
              :disabled="inputOperate(scope.row)"
            ></el-input>
          </el-form-item>
        </template>
        <template v-slot:totalCount="scope">
          <el-form-item
            style="margin-bottom: 20px"
            :prop="'tableList.' + scope.$index + '.totalCount'"
          >
            <el-input
              v-model="scope.row.totalCount"
              @input="totalCountChange(scope.$index, scope.row, 'totalCount')"
              :disabled="schemeTableTool(scope.row)"
              type="number"
              :min="1"
            ></el-input>
            <!-- :disabled="type == 'view' || scope.row.isApply == 1" -->
          </el-form-item>
        </template>
        <template v-slot:measureUnit="scope">
          <el-form-item
            style="margin-bottom: 20px"
            :prop="'tableList.' + scope.$index + '.measureUnit'"
          >
            <el-input
              v-if="scope.row.typeId != 2"
              v-model="scope.row.measureUnit"
              :disabled="type == 'view'"
            ></el-input>
            <span v-if="scope.row.typeId == 2">
              {{ scope.row.measureUnit }}
            </span>
          </el-form-item>
        </template>
        <template v-slot:singlePrice="scope">
          <el-form-item
            style="margin-bottom: 20px"
            :prop="'tableList.' + scope.$index + '.singlePrice'"
          >
            <el-input
              v-model="scope.row.singlePrice"
              @input="totalCountChange(scope.$index, scope.row, 'singlePrice')"
              :disabled="inputOperate(scope.row)"
              type="number"
              :min="0"
            ></el-input>
          </el-form-item>
        </template>
        <!-- 现在如果是查主数据的话 还可以选择仓库 -->
        <template v-slot:warehouseId="scope">
          <el-form-item
            v-if="scope.row.typeId == '2'"
            style="margin-bottom: 20px"
            :prop="'tableList.' + scope.$index + '.warehouseId'"
          >
            <el-select
              v-if="obtain == '主数据'"
              v-model="scope.row.warehouseId"
              placeholder="请选择仓库"
              class="w100"
              :disabled="schemeTableTool(scope.row)"
            >
              <el-option
                v-for="item in scope.row.warehouseList"
                @click="warehouseChange(item, scope.row, scope.$index)"
                :key="item.warehouseId"
                :label="item.warehouseName"
                :value="item.warehouseId"
              ></el-option>
              <!-- :disabled="type == 'view' || scope.row.isApply == 1" -->
            </el-select>
            <el-input
              v-model="scope.row.warehouseName"
              disabled
              v-else
            ></el-input>
          </el-form-item>
          <el-form-item
            v-else
            style="margin-bottom: 20px"
            :prop="'tableList.' + scope.$index + '.warehouseId'"
          >
            <el-select
              v-model="scope.row.warehouseId"
              placeholder="请选择仓库"
              class="w100"
              :disabled="schemeTableTool(scope.row)"
            >
              <!-- :disabled="type == 'view' || scope.row.isApply == 1" -->
              <el-option
                v-for="item in scope.row.warehouseList"
                @click="warehouseChange(item, scope.row, scope.$index)"
                :key="item.warehouseId"
                :label="item.warehouseName"
                :value="item.warehouseId"
              ></el-option>
            </el-select>
          </el-form-item>
        </template>
        <template v-slot:action="{ row, $index }">
          <el-link
            type="danger"
            :underline="false"
            icon="el-icon-delete"
            v-if="schemeOperate(row)"
            @click="del(row, $index)"
            >删除</el-link
          >
          <!--  v-if="type != 'view' && row.isApply != 1 && source != '报工信息'" -->
        </template>
        <template v-slot:headerName="{ column }">
          <span class="is-required">{{ column.label }}</span>
        </template>
      </ele-pro-table>
    </el-form>
    <product-list
      ref="productListRef"
      classType="1"
      :is-get-inventory-total="true"
      @changeParent="confirmChoose"
      itemType="5"
      :isFirstRefreshTable="true"
    ></product-list>
    <!-- <applyForSpare ref="edit" :inlet="1" /> -->
  </div>
</template>

<script>
  import {
    getWarehouseOutStock,
    getIdWarehouseList
  } from '@/api/saleManage/saleorder';
  import AssetsDialog from './AssetsDialog.vue';
  import { getByCode } from '@/api/system/dictionary-data';
  import productList from '@/BIZComponents/product-list.vue';

  export default {
    components: {
      //   applyForSpare,
      AssetsDialog,
      productList
    },
    props: {
      type: '',
      // 数据来源
      source: {
        default: '',
        type: String
      },
      // 表格权限操作 状态
      state: {
        default: '',
        type: String
      },
      detailList: {
        type: Array,
        default: () => []
      },
      obtain: {
        type: String,
        default: '主数据'
      }
    },
    data() {
      return {
        loading: false,
        form: {
          tableList: []
        },
        totalPrice: 0,
        typeIdList: []
      };
    },
    created() {
      this.getLevelCode('after_sales_project');
    },
    computed: {
      columnsDetail() {
        return [
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'typeId',
            label: '项目',
            align: 'center',
            width: 120,
            slot: 'typeId',
            showOverflowTooltip: true
          },
          {
            prop: 'code',
            label: '编码',
            align: 'center',
            slot: 'code',
            minWidth: 150,
            showOverflowTooltip: true
          },

          {
            prop: 'name',
            label: '名称',
            align: 'center',
            minWidth: 250,
            slot: 'name',
            showOverflowTooltip: true,
            headerSlot: 'headerName'
          },
          {
            prop: 'categoryModel',
            label: '型号',
            width: 150,
            align: 'center',
            slot: 'categoryModel',
            showOverflowTooltip: true
          },
          {
            prop: 'specification',
            width: 150,
            label: '规格',
            slot: 'specification',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'content',
            minWidth: 300,
            slot: 'content',
            label: '详细内容',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'warehouseId',
            minWidth: 170,
            slot: 'warehouseId',
            label: '仓库',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'warehouseNum',
            minWidth: 100,
            label: '库存',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'totalCount',
            slot: 'totalCount',
            width: 100,
            label: '数量',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'measureUnit',
            width: 120,
            slot: 'measureUnit',
            label: '单位',
            align: 'center',
            showOverflowTooltip: true
          },

          {
            prop: 'singlePrice',
            slot: 'singlePrice',
            width: 120,
            label: '单价(元)',
            align: 'center',
            showOverflowTooltip: true
          },

          {
            prop: 'settlementPrice',
            width: 80,
            label: '合计(元)',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 150,
            align: 'center',
            resizable: false,
            slot: 'action',
            fixed: 'right',
            showOverflowTooltip: true,
            show: this.type != 'view'
          }
        ];
      },
      // 选择按钮显示
      chooseShow() {
        return (scope) => {
          if (this.source == '配件回收') {
            return true;
          }
          let flag =
            scope.row.typeId == 2 &&
            scope.row.isApply != 1 &&
            this.type == 'edit';
          return flag;
        };
      },

      // 添加 按钮显示权限
      buttonJud() {
        if (this.source == '派单进来') {
          return true;
        }
        let flag = this.type != 'view' && this.source != '报工信息';
        return flag;
      },
      // 方案列表删除权限
      schemeOperate() {
        return (row) => {
          if (this.source == '配件回收') {
            return true;
          }
          let flag =
            this.type != 'view' &&
            row.isApply != 1 &&
            this.source != '报工信息';
          return flag;
        };
      },
      // 方案表格操作权限
      schemeTableTool() {
        return (row) => {
          let flag = this.type == 'view' || row.isApply == 1;
          return flag;
        };
      },
      // input输入权限
      inputOperate() {
        return (row) => {
          let flag = this.type == 'view' || row.isApply == 1;
          return flag;
        };
      }
    },
    watch: {
      detailList: {
        handler(newVal) {
          this.form.tableList = newVal;
        },
        immediate: true
      }
    },
    mounted() {
      if (this.source == '配件回收') {
        this.typeIdList = [
          {
            label: '零配件',
            value: '2'
          }
        ];
      }
      if (this.detailList.length > 0) {
        this.form.tableList = this.detailList;
      }
    },
    methods: {
      init(row) {},
      async getLevelCode(code) {
        try {
          const res = await getByCode(code);
          if (res.code == 0) {
            let list = Object.values(res.data).map((el) => {
              let k = Object.keys(el)[0];
              let v = Object.values(el)[0];
              return {
                label: v,
                value: k
              };
            });
            this.typeIdList = list;
          }
        } catch (err) {
          this.$message.error(err.message);
        }
      },
      typeIdChange(row, index) {
        let obj = {
          typeId: row.typeId,
          code: '',
          name: '',
          categoryModel: '',
          specification: '',
          content: '',
          totalCount: 1,
          measureUnit: '',
          singlePrice: '',
          settlementPrice: ''
        };
        let o = this.typeIdList.find((item) => item.value == row.typeId);
        if (o.value != 2) {
          obj.name = o.label;
        }
        this.$set(this.form.tableList, index, obj);
      },
      getValidate() {
        return new Promise((resolve, reject) => {
          this.$refs.form.validate((valid, obj) => {
            if (obj) {
              let messages = Object.keys(obj).map((key) => obj[key][0]);
              if (messages.length > 0) {
                this.$message.warning(messages[0].message);
              }
            }
            if (!valid) {
              reject(false);
            } else {
              resolve(true);
            }
          });
        });
      },
      addBank() {
        this.form.tableList.push({
          typeId: '2',
          code: '',
          name: '',
          categoryModel: '',
          specification: '',
          content: '',
          totalCount: 1,
          measureUnit: '',
          singlePrice: '',
          settlementPrice: ''
        });
      },
      async addEquipment(row, index) {
        // const res = await parameterGetByCode({
        //   code: 'after_sales_accessory_source'
        // });
        this.currentIndex = index;
        if (this.obtain == '仓库') {
          this.$refs.productListRef.open('', index, '0');
        } else {
          this.$refs.productListRef.open('', index, '1');
        }
      },
      getTableValue() {
        return this.form.tableList;
      },
      setTableValue(val) {
        this.$set(this.form, 'tableList', val);
        this.form.tableList.forEach(async (item, index) => {
          if (item.typeId == 2) {
            this.$set(
              this.form.tableList[index],
              'warehouseList',
              await getIdWarehouseList({
                categoryId: item.categoryId
              })
            );
            if (item.warehouseId) {
              this.$set(
                this.form.tableList[index],
                'warehouseNum',
                await getWarehouseOutStock({
                  warehouseId: item.warehouseId,
                  code: item.code
                })
              );
            }
          }
        });
        // ***
        this.calculatePrice();
      },
      totalCountChange(index, data, name) {
        data[name] = data[name].replace(/[^\d]/g, '').replace(/^0+/, '') || '0';
        let row = this.form.tableList[index];
        if (row.totalCount && row.singlePrice) {
          row.settlementPrice = row.totalCount * row.singlePrice;
        } else {
          row.settlementPrice = 0;
        }
        this.$set(
          this.form.tableList[index],
          'settlementPrice',
          row.settlementPrice || 0
        );
        this.calculatePrice();
      },
      clearList() {
        this.form.tableList = [];
      },
      // 计算汇总价格 ***
      calculatePrice() {
        let totlal = 0;
        this.form.tableList.map((el) => (totlal += el.settlementPrice));
        this.totalPrice = totlal;
      },
      del(row, index) {
        this.form.tableList.splice(index, 1);
      },
      async confirmChoose(data) {
        this.$set(this.form.tableList, this.currentIndex, data[0]);
        this.$set(
          this.form.tableList[this.currentIndex],
          'categoryModel',
          data[0].modelType
        );
        this.$set(
          this.form.tableList[this.currentIndex],
          'categoryId',
          data[0].id
        );
        this.$set(
          this.form.tableList[this.currentIndex],
          'measureUnit',
          data[0].measuringUnit
        );

        this.$set(
          this.form.tableList[this.currentIndex],
          'warehouseList',
          await getIdWarehouseList({
            categoryId: data[0].id
          })
        );
        if (this.form.tableList[this.currentIndex]?.warehouseList?.length) {
          this.warehouseChange(
            this.form.tableList[this.currentIndex].warehouseList[0],
            this.form.tableList[this.currentIndex],
            this.currentIndex
          );
        }

        this.$set(this.form.tableList[this.currentIndex], 'typeId', '2');
        this.$forceUpdate();
      },
      async warehouseChange(item, row, index) {
        this.$set(
          this.form.tableList[index],
          'warehouseName',
          item.warehouseName
        );
        this.$set(this.form.tableList[index], 'warehouseId', item.warehouseId);
        this.$set(
          this.form.tableList[index],
          'warehouseNum',
          await getWarehouseOutStock({
            warehouseId: item.warehouseId,
            code: row.code
          })
        );
      }
    }
  };
</script>
<style lang="scss" scoped>
  :deep(.el-table__body .el-form-item__content) {
    margin-left: 0px !important;
  }
  :deep(.el-table__body .el-form-item) {
    margin-bottom: 0px !important;
  }
  .total_price {
    margin-left: 24px;
  }

  .toobar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-right: 16px;
  }

  .toobar_r {
    justify-content: flex-end;
  }
</style>
